Rewrite for loop with find function

The question:
  1. See the following code. Rewrite the code in one line using the find function.
x=[-1 3 7 2 4 0];
v=[];
for i=1:length(x)
ifx(i)<=2
v=[v, x(i)];
end
end
I have tried x=[-1 3 7 2 4 0]; find(x<=2)
which returns 1 4 6. What I need it to display is -1 2 0
How would I do this? thanks!

답변 (1개)

Erivelton Gualter
Erivelton Gualter 2019년 11월 18일

1 개 추천

The function find returns the indeces according to the condition. So, in order to diplay the values, you might use the following:
x(find(x<=2))
Here is more information.

댓글 수: 4

Johnathan Pryor
Johnathan Pryor 2019년 11월 18일
I tried that and it doesnt work unfortunately and the link to more information is broken
Johnathan Pryor
Johnathan Pryor 2019년 11월 18일
Thanks for leading me in the right direction. I used x=[-1 3 7 2 4 0]; x(find(x<=2)) and it worked
Erivelton Gualter
Erivelton Gualter 2019년 11월 18일
편집: Erivelton Gualter 2019년 11월 19일
I fixed the link. It is just the find document. Glad it worked.
If it was helpful, please accept the answer.
Vladimir Sovkov
Vladimir Sovkov 2019년 11월 19일
"find" is redundant here. You can just use
x(x<=2);

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2019년 11월 18일

댓글:

2019년 11월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by