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

感情迁移 提交于 2019-12-06 15:02:40

问题


I have a sat of matrices and I want to extract only a part of the matrix that satisfy a condition.

For example: values of the 150x180 matrix goes from 0 to 2.80 and I only want those between 1.66 and 1.77 I want to keep the values within the rang in their original location in the original matrix and set the other to zero.

can anybody help me please.

Thank you


回答1:


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.



来源:https://stackoverflow.com/questions/12781736/how-to-extract-a-part-of-a-matrix-with-condition-in-matlab

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