Outputting even numbers using logical indexing and rem.

10 次查看(过去 30 天)
I am having troubles figuring out How can I output only the even numbers in an array using logical indexing and the rem function?
Thanks!!

采纳的回答

Image Analyst
Image Analyst 2015-12-11
Try this:
% Create sample data.
m = randi(9, 1, 20)
% Get the logical indexes of even numbers ONLY.
evenLogicalIndexes = rem(m,2) == 0;
% Extract only those even elements from m
mEven = m(evenLogicalIndexes)
  2 个评论
heehaw
heehaw 2015-12-11
Oh I see now.
The rem(A,2) provides a 0 if its even and 1 if its odd. So in order to change it so its the other way around we use a logical operator == .
Thanks!!
Image Analyst
Image Analyst 2015-12-11
You could also use ~ to invert it:
oddLogicalIndexes = ~rem(m,2);
Same thing. Perhaps this way is slightly faster for very large arrays.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by