How to compare row values in a column ?
2 views (last 30 days)
Show older comments
Hi, How can I compare whether an element of a vector is greater, or less than the previous one and if equal check one before the previous and so on.
A=[2; 3; 4; 2; 2; 3; 7; 3; 3] size 10x1 could be 10e5x1
Out=[1; 1; -1; -1; 1; 1; -1; -1] size 9x1
3 > 2 then 1 in out ; 4>3 the same; 2<4 then -1; 2=2 then go back to a number that is not 2(it may not be always the direct preceding number if there is a sequence of 2s for like 10^n rows) , in this case 4 is the first number so use 4 , 2<4 then -1 and so on
0 Comments
Accepted Answer
Image Analyst
on 27 Dec 2015
Here's one easy, straightforward way:
A=[2, 3, 4, 2, 2, 3, 7, 3, 3] % size 10x1 could be 10e5x1
% out is the sign of the difference
out = sign(diff(A))
% Fill in zeros with the last known good sign
for k = 2 : length(out)
if out(k) == 0
out(k) = out(k-1);
end
end
% Print to command window
out
The only requirement is that you don't start off with one or more zeros because there is no prior sign to use for "out" in that case.
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!