A = [-1 -2 0 1 2];
B = A(A<0);
What does A(A<0) mean exactly? and is there a way to do its function with an if statement? because I tried this and it did not work.
if A<0
B = A;
end

댓글 수: 1

Stephen23
Stephen23 2021년 4월 27일
편집: Stephen23 2021년 4월 27일
"What does A(A<0) mean exactly?"
A(A<0)
^^^ logical index
^^ ^ indexing into A
Basic MATLAB concepts, like how to use indexing, are explained here:
"and is there a way to do its function with an if statement?"
It could be done with a bit of effort, but that would be a very poor use of MATLAB.

댓글을 달려면 로그인하십시오.

 채택된 답변

Dyuman Joshi
Dyuman Joshi 2021년 4월 27일
편집: Dyuman Joshi 2021년 4월 28일

2 개 추천

B = A(A<0) means to allocate all the elements of A which are less than zero to B.
In case you want to use if statement to obtain the same, use a for loop as follows -
B=[];
for i=1:numel(A)
if A(i)<0
B = [B A(i)];
end
end
However, using B = A(A<0) should be opted.

댓글 수: 2

Mashari Alharbi
Mashari Alharbi 2021년 4월 27일
Thank you for your answer, but what does x mean in the alternative way?
Dyuman Joshi
Dyuman Joshi 2021년 4월 28일
My bad, that is supposed to be A and not x. I have edited it.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 4월 27일

2 개 추천

That operation is logical indexing. Also see the "Indexing with Logical Values" section on this documentation page for more information.

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2021년 4월 27일

댓글:

2021년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by