필터 지우기
필터 지우기

comparing matrix elements in order

조회 수: 2 (최근 30일)
Antonio
Antonio 2014년 12월 28일
댓글: Shoaibur Rahman 2014년 12월 28일
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