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

35 次查看(过去 30 天)
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!

采纳的回答

Adam Danz
Adam Danz 2020-1-16
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}

更多回答(1 个)

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

类别

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