oactve: modify each element according to a simple condition - octave

New to octave here.
I have a matrix X, would like to change all the element (as a numeric number) like this: if the value of the element is greater than 10, change it to 10, otherwise, keep the same value.
In theory I can do a two loops and go through each element. Wonder if there is a simple way of doing this.

This can be done very simply, and more efficiently, with logical indexing:
A(A>10) = 10;
Another option is to use the min function:
A = min(A,10);

EDIT:
I looks like the idiomatic way to do that is using logical indexing:
A(A>10)=10
Use Function Application (#arrayfun):
> A=[10, 20, 30; 9, 13, 8]
> arrayfun (#(x) ifelse (x>10, 10, x), A)
ans =
10 10 10
9 10 8

Related

What is the best way to calculate the duration from incode/outcode in MySQL?

I have written the following to calculate the duration from incode/outcode but was wondering if there was a better way of calculating this.
As TIMEDIFF() is a time specific function, I was only able to use it to calculate the difference between the fist 9 characters. I then subtract the last two characters and add them back to the 'Duration'.
HH:MM:SS:FF (FF for frames) and the framerate is 25fps.
incode = '10:00:01:00'
outcode = '10:01:05:02'
select CONCAT(SUBSTR(TIMEDIFF(outcode, incode), 1, 8), ':',
LPAD((SUBSTR(outcode, 10, 11) - SUBSTR(incode, 10, 11)), 2, 0)) as 'Duration';
Duration should be:
00:01:04:02
MySQL Version: 5.5+
If you're using 5.5.x or later then you can consider the following...
SET #timecode_2 = '10:01:05:02';
SELECT SEC_TO_TIME(TIME_TO_SEC(SUBSTRING_INDEX(#timecode_2,':',3))+SUBSTRING_INDEX(#timecode_2,':',-1)*0.04) x;
Outputs:
x
10:01:05.0800000

Finding Median WITHOUT Data Structures

(my code is written in Java but the question is agnostic; I'm just looking for an algorithm idea)
So here's the problem: I made a method that simply finds the median of a data set (given in the form of an array). Here's the implementation:
public static double getMedian(int[] numset) {
ArrayList<Integer> anumset = new ArrayList<Integer>();
for(int num : numset) {
anumset.add(num);
}
anumset.sort(null);
if(anumset.size() % 2 == 0) {
return anumset.get(anumset.size() / 2);
} else {
return (anumset.get(anumset.size() / 2)
+ anumset.get((anumset.size() / 2) + 1)) / 2;
}
}
A teacher in the school that I go to then challenged me to write a method to find the median again, but without using any data structures. This includes anything that can hold more than one value, so that includes Strings, any forms of arrays, etc. I spent a long while trying to even conceive of an idea, and I was stumped. Any ideas?
The usual algorithm for the task is Hoare's Select algorithm. This is pretty much like a quicksort, except that in quicksort you recursively sort both halves after partitioning, but for select you only do a recursive call in the partition that contains the item of interest.
For example, let's consider an input like this in which we're going to find the fourth element:
[ 7, 1, 17, 21, 3, 12, 0, 5 ]
We'll arbitrarily use the first element (7) as our pivot. We initially split it like (with the pivot marked with a *:
[ 1, 3, 0, 5, ] *7, [ 17, 21, 12]
We're looking for the fourth element, and 7 is the fifth element, so we then partition (only) the left side. We'll again use the first element as our pivot, giving (using { and } to mark the part of the input we're now just ignoring).
[ 0 ] 1 [ 3, 5 ] { 7, 17, 21, 12 }
1 has ended up as the second element, so we need to partition the items to its right (3 and 5):
{0, 1} 3 [5] {7, 17, 21, 12}
Using 3 as the pivot element, we end up with nothing to the left, and 5 to the right. 3 is the third element, so we need to look to its right. That's only one element, so that (5) is our median.
By ignoring the unused side, this reduces the complexity from O(n log n) for sorting to only O(N) [though I'm abusing the notation a bit--in this case we're dealing with expected behavior, not worst case, as big-O normally does].
There's also a median of medians algorithm if you want to assure good behavior (at the expense of being somewhat slower on average).
This gives guaranteed O(N) complexity.
Sort the array in place. Take the element in the middle of the array as you're already doing. No additional storage needed.
That'll take n log n time or so in Java. Best possible time is linear (you've got to inspect every element at least once to ensure you get the right answer). For pedagogical purposes, the additional complexity reduction isn't worthwhile.
If you can't modify the array in place, you have to trade significant additional time complexity to avoid avoid using additional storage proportional to half the input's size. (If you're willing to accept approximations, that's not the case.)
Some not very efficient ideas:
For each value in the array, make a pass through the array counting the number of values lower than the current value. If that count is "half" the length of the array, you have the median. O(n^2) (Requires some thought to figure out how to handle duplicates of the median value.)
You can improve the performance somewhat by keeping track of the min and max values so far. For example, if you've already determined that 50 is too high to be the median, then you can skip the counting pass through the array for every value that's greater than or equal to 50. Similarly, if you've already determined that 25 is too low, you can skip the counting pass for every value that's less than or equal to 25.
In C++:
int Median(const std::vector<int> &values) {
assert(!values.empty());
const std::size_t half = values.size() / 2;
int min = *std::min_element(values.begin(), values.end());
int max = *std::max_element(values.begin(), values.end());
for (auto candidate : values) {
if (min <= candidate && candidate <= max) {
const std::size_t count =
std::count_if(values.begin(), values.end(), [&](int x)
{ return x < candidate; });
if (count == half) return candidate;
else if (count > half) max = candidate;
else min = candidate;
}
}
return min + (max - min) / 2;
}
Terrible performance, but it uses no data structures and does not modify the input array.

How can I round an integer to the nearest 1000 in Pascal?

I've got a Integer variable in Pascal. Is there any possible function I can use that can round that value to the nearest 1000, for example:
RoundTo(variable, 1000);
Does anything of the sort exist? Or is there another method I should try using?
Thanks!
The general solution for this kind of problem is to scale before and after rounding, e.g.
y = 1000 * ROUND(x / 1000);
Use RoundTo(variable, 3).
The second parameter specifies the digits you want to round to. Since you want to round to 1000 = 103 you need to specifiy 3, not 1000.
The documentation for RoundTo says:
function RoundTo(const AValue: Extended; const ADigit: TRoundToEXRangeExtended): Extended;
Rounds a floating-point value to a specified digit or power of ten using "Banker's rounding".
ADigit indicates the power of ten to which you want AValue rounded. It can be any value from –37 to 37 (inclusive).
The following examples illustrate the use of RoundTo:
RoundTo(1234567, 3) = 1235000
(I left out parts not relevant to your question)
Side-note: RoundTo uses Banker's round, so RoundTo(500, 3) = 0 and RoundTo(1500, 3) = 2000.
x = 1000*(x/1000), or x = x - (x mod 1000)

Prolog binary addition without cuts(!)

I am trying to figure out how to add two binary numbers together which are represented as lists. For example:
addNumbers([1,0,1], [1,1,0,0], X). should return X = [1,0,0,0,1].
We are not aloud to use cuts(!) to solve this problem. So I know I have to implement a adder of sorts. Right now I have adding Digits implemented with its needed predicates:
addDigits(A,B,X,Y) :- myXor(A,B,X), myAnd(A,B,Y).
myAnd(A,B,R) :- A == 1, B == 1, R is 1.
myAnd(A,B,R) :- A == 0, B == 0, R is 0.
myAnd(A,B,R) :- A == 1, B == 0, R is 0.
myAnd(A,B,R) :- A == 0, B == 1, R is 0.
myOr(A,B,R) :- A == 0, B == 0, R is 0.
myOr(A,B,R) :- A == 0, B == 1, R is 1.
myOr(A,B,R) :- A == 1, B == 0, R is 1.
myor(A,B,R) :- A == 1, B == 1, R is 1.
This correctly returns X as the sum of the 2 binary digits and Y as the carry. Now I know I need this for my adder. Now to actually implement addDigits is where I am stuck. This is currently what I have but does not work. NOTE: The hint was the start the the LSB's but I currently don't do that.
addNumbers([HA|TA],[HB|TB],X) :- adder(HA,HB,Cin,Sum,Cout,X),
append(Sum, X, X),
addNumbers(TA,TB,X).
adder(X,Y,Cin,Sum,Cout) :- addDigits(X,Y,Sum1,Carry1),
addDigits(Sum1, Cin, Sum, Carry2),
myOr(Carry1, Carry2, Cout).
Any help/suggestions would be appreciated.
Cheers
You are on a good track. Your major problem is to understand typical Prolog recursion.
But first, your binary functions: They are correct, but it's easier and more readable like this (you are missing this one anyway):
myXor(1,0,1).
myXor(0,1,1).
myXor(1,1,0).
myXor(0,0,0).
There is a typo in your myOr in the fourth case: you spelled it with a lower case "o". With this defined, your adder does indeed work correctly!
Now, about the recursion: You really need to start with the LSB, otherwise you can't even know which bits to add, because the numbers are not necessarily the same length. Fortunately, you can do this easily by wrapping the call in reverses:
addNumbers(N1, N2, Sum) :-
reverse(N1, N12),
reverse(N2, N22),
addNumbers(N12, N22, 0, [], Sum0),
reverse(Sum0, Sum).
This is quite a common pattern in Prolog: addNumbers/3 calling addNumbers/5 with more parameters needed for the recursion. The "0" is the initial carry, the [] is the accumulator for the result.
Here is addNumbers/5, with some changes from your version:
addNumbers([HA|TA],[HB|TB],Cin,X0,X) :-
adder(HA,HB,Cin,Sum,Cout),
append(X0, [Sum], X1),
addNumbers(TA,TB,Cout,X1,X).
First, note that you need to receive Cin as an input parameter here! Also, we have X0 as an "accumulator" variable, that is, it grows longer with each recursive call. The final call will have the result, so it can make it into the output variable. For that, you also need the base cases:
addNumbers([],B,Cin,X0,X) :- % TODO: Respect Cin
append(X0,B,X).
addNumbers(A,[],Cin,X0,X) :- % TODO: Respect Cin
append(X0,A,X).
See how the result of append is not X1 (another intermediate variable) as above, but X? This is because its the final result, and it will be unified with the same X all the way down the call stack, and this way it becomes the output of the whole addNumbers/5 call!
I left it unfinished though, so that there is some (little) work for you left: Also the base cases need to take Cin into account...

Matlab | Matrix Function of Several Variables

I'm working on Matlab and I need to define a matrix function that depends on several variables.
For example, I have this vectors:
t=[1,2,3,4,5,6,7,8,9,10]
y=[1,2,3,4,5,6,7,8,9,10]
That can contain any real numbers or have any length (same length for t and y, I called it NumData).
I have a function that depends on some parameters P1, P2,...,P5. What I want to do is to form a Matrix (NumData x 5) that depends of p, a vector of parameters:
I don't know how to step further. I thought of define a Matrix:
Matrix = ones(NumData,NumParameters)
But when I try to assign, for example
Matrix(1,3) = p(1)+3*p(2)
I got an error.
I tried to define:
Matrix(1,3)=#(p) p(1)+3*p(2)
But it's useless...
I tried to define the matrix in code, like this:
J=#(p) [1 1 1 exp(-p(5)) -p(4)*exp(-p(5))
1 2 4 exp(-2*p(5)) -p(4)*exp(-2*p(5))
1 3 9 exp(-3*p(5)) -p(4)*exp(-3*p(5))
1 4 16 exp(-4*p(5)) -p(4)*exp(-4*p(5))
1 5 25 exp(-5*p(5)) -p(4)*exp(-5*p(5))]
but it isn't good because this is for a specific case...
My main goal is to form J from t vector, and that J depends on the vector parameter p so I can evaluate later
A= J(1,2,1,2,2)
for example, and then factorize A as QR.
Do you have any suggestions? Or I am asking too much for Matlab?
I'm not 100% sure of what you are trying to do, but let me give you some examples of things that will work, in the hopes that it can help you a bit.
p=[1 2 3 4 5];
M=zeros(3,2);
M=[p(1) p(2) p(5); p(3)/p(2) p(5)^p(2) exp(p(3))]