How to compare each element of a matrix with a number ?

35 vues (au cours des 30 derniers jours)
Riccardo Busin
Riccardo Busin le 16 Jan 2020
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!

Réponse acceptée

Adam Danz
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
Riccardo Busin
Riccardo Busin le 16 Jan 2020
Thanks for your help!
Adam Danz
Adam Danz le 17 Jan 2020
Glad I could help!

Connectez-vous pour commenter.

Plus de réponses (1)

Naveen Miriyala
Naveen Miriyala le 12 Mai 2022
A=[2 3 4 5];
T=6;
A=[A,A<6]

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by