How to compare each element of a matrix with a number ?
조회 수: 15 (최근 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!
댓글 수: 0
채택된 답변
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!