How to compare each element of a matrix with a number ?
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Riccardo Busin
le 16 Jan 2020
Réponse apportée : Naveen Miriyala
le 12 Mai 2022
Hello everyone!
I have this problem:
I have this matrix (10x1 double): A = [10; 20; 30; 40; 50; 60; 70; 80; 90; 100]
I would like to compare each element in this matrix with numbers. Precisely like this:
If the elements of A <= 50 then it is false, if the elements of A> 50 then it is true. So get this as a final result: B=[10 false; 20 false; 30 false; ......; 100 true]
How could I do ?
I use this code (but it dosen't work):
B=[ ]
if all(A <= 50)
B = ('False');
else
if all(A > 50)
B = ('True');
end
end
Thanks for the answers!
0 commentaires
Réponse acceptée
Adam Danz
le 16 Jan 2020
Since A are of class double and the </> comparisons will produce logical values, you cannot combine them in a matrix.
Instead, here are 3 options.
Option 1: Matrix (converting logical values to double)
A = [10; 20; 30; 40; 50; 60; 70; 80; 90; 100];
B = [A, A > 50];
% Result
% B =
% 10 0
% 20 0
% 30 0
% 40 0
% 50 0
% 60 1
% 70 1
% 80 1
% 90 1
% 100 1
Option 2: Table
A = [10; 20; 30; 40; 50; 60; 70; 80; 90; 100];
T = table(A, A > 50, 'VariableNames',{'A','TF'});
% Result
% T =
% A TF
% ___ _____
%
% 10 false
% 20 false
% 30 false
% 40 false
% 50 false
% 60 true
% 70 true
% 80 true
% 90 true
% 100 true
Option 3: Cell array
A = [10; 20; 30; 40; 50; 60; 70; 80; 90; 100];
B = {A, A > 50};
% Result
% B =
% {10×1 double} {10×1 logical}
2 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Resizing and Reshaping 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!