如何在Matlab中使用条件提取矩阵的一部分 [英] How to extract a part of a matrix with condition in Matlab
问题描述
我有一些矩阵,我只想提取满足条件的一部分矩阵.
I have a sat of matrices and I want to extract only a part of the matrix that satisfy a condition.
例如:150x180
矩阵的值从0
到2.80
,我只希望在1.66
和1.77
之间的值
我想将这些值保留在原始矩阵的原始位置范围内,并将另一个设置为零.
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.
有人可以帮我吗?
谢谢
推荐答案
您可以使用逻辑索引.首先,找到不满足您条件的A
条目.接下来,使用A(idx)
将其更改为0:
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;
或更简单些,如Rody Oldenhuis所建议的,您可以将逻辑表达式直接包含在矩阵引用中:
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;
这将产生更短,更简洁的代码,但不会产生更快的代码:MATLAB仍显式创建逻辑索引变量,但随后将其清除.
This yields a shorter and cleaner code, but not a faster code: MATLAB still explicitly creates the logical index variable, but clears it afterwards.
这篇关于如何在Matlab中使用条件提取矩阵的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!