comparing matrix elements in order

1 次查看(过去 30 天)
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!!!

采纳的回答

Shoaibur Rahman
Shoaibur Rahman 2014-12-28
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 个评论
Image Analyst
Image Analyst 2014-12-28
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
Shoaibur Rahman 2014-12-28
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.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2014-12-28
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by