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!!!
0 个评论
采纳的回答
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
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
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!