How to extract a part of a matrix with condition in Matlab

孤街醉人 提交于 2019-12-04 20:41:51

You can use logical indexing. First, find A entries that do not satisfy your conditions. Next, using A(idx) change them to 0:

% example matrix
A = 2.8*rand(150, 180);

% find entries meeting some criterion
idx = A<1.66 | A>1.77;
A(idx) = 0;

Or simpler, as Rody Oldenhuis suggested, you can include the logical expression directly in the matrix reference:

A(A<1.66 | A>1.77) = 0;

This yields a shorter and cleaner code, but not a faster code: MATLAB still explicitly creates the logical index variable, but clears it afterwards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!