I want to know how this code is working.
2 次查看(过去 30 天)
显示 更早的评论
I am new to MATLAB. To improve my skills I am practicing with simple problems. One problem is extracting even and odd numbers from a vector.For e.g. I wrote this code to extract odd and even numbers from a vector.
A=linspace(1,1000,1000);
Odd=[];
Even=[];
for i=1:length(A)
if rem(A(i),2)~=0;
Odd=[Odd;A(i)];
else
Even=[Even;A(i)];
end
end
A colleague pointed out that there is an even easier way of doing this..(there could be many)
Odd=A(rem(A(:),2)~=0);
Even=A(rem(A(:),2)==0);
I don't understand how this code works. The part rem(A(:),2)~=0 gives a logical array. How does index of logical array ultimately give odd and even numbers?
0 个评论
采纳的回答
Stephan
2018-7-17
Hi,
lhe logical array inside the A(...) gives back all the values where the index represented by the logical array is true. That is why this works.
To learn more about this check this: https://de.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html
Best regards
Stephan
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!