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

9 Ansichten (letzte 30 Tage)
Riccardo Busin
Riccardo Busin am 16 Jan. 2020
Beantwortet: Naveen Miriyala am 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!

Akzeptierte Antwort

Adam Danz
Adam Danz am 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}

Weitere Antworten (1)

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

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by