comparing matrix elements in order
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Antonio
le 28 Déc 2014
Commenté : Shoaibur Rahman
le 28 Déc 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 commentaires
Réponse acceptée
Shoaibur Rahman
le 28 Déc 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 commentaires
Image Analyst
le 28 Déc 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
le 28 Déc 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.
Plus de réponses (1)
Image Analyst
le 28 Déc 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 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!