comparing matrix elements in order
1 view (last 30 days)
Show older comments
Antonio
on 28 Dec 2014
Commented: Shoaibur Rahman
on 28 Dec 2014
Hi, i have a one column matrix and it should go from n to the top, every number in that column should be equal or higher than the one avobe so for example this one
A = [2000 500 300 300 1]'
so what i need is a way of comparing the number below to the one above and see if it is equal or higher then when it goes over all the matrix with that requirement it should display "its in order" if it doesnt fit it should display "is not in order". the example should say "its in order" The matrix can be of n numbers but always on one column
Thanks!!!
0 Comments
Accepted Answer
Shoaibur Rahman
on 28 Dec 2014
A = [2000 500 300 300 1]';
A1 = sort(A,'descend');
if sum(A==A1)==length(A)
disp('in order')
else disp('not in order')
end
3 Comments
Image Analyst
on 28 Dec 2014
May be, but it's not . Just try it with
A=[1,3,3,3,3]
Your code says it's not in order. You can't just check the sum, you need to use all() like I did in my code below.
Shoaibur Rahman
on 28 Dec 2014
According to the example vector in the question, it should return 'in order' if A(k)>=A(k+1) for all kth and (k+1)th elements. In that sense, for A=[1,3,3,3,3], the output should be 'not in order', which is displayed by the code. However, there might be bit contradiction between the example and explanation in the question.
In this case, all() can be used as an alternative, of course, but not essential. There might be many more alternatives.
More Answers (1)
Image Analyst
on 28 Dec 2014
Try using diff() (to look for positive differences), then all (to make sure they're all positive.
% Define a "not in order" A
A = [2000 500 300 300 1]'
if all(diff(A) >= 0)
uiwait(helpdlg('It is in order'));
else
uiwait(helpdlg('It is not in order'));
end
% Define an "in order" A.
A = sort(randi(99, 10, 1), 'Ascend')
if all(diff(A) >= 0)
uiwait(helpdlg('It is in order'));
else
uiwait(helpdlg('It is not in order'));
end
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!