Rewrite for loop with find function
6 次查看(过去 30 天)
显示 更早的评论
The question:
- 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!
0 个评论
回答(1 个)
Erivelton Gualter
2019-11-18
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 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!