我有一个矩阵,我想选择一系列元素。例如,我想选择所有低于 182 的元素并交换/更改它们。有人知道在 matlab 中执行此操作的简单方法或命令吗?
谢谢
Since you say "swap", I understand you mean a vector, not a matrix. You can do it as follows:
x = [ 1 34 66 22 200 55 301 ]; % data
[ values, ind ] = find(x<182);
x(ind) = x(ind(end:-1:1));
To simply replace them by another value such as NaN, do as follows. Note that this works also for matrices:
x = [ 1 34 66 22 200 55 301 ]; % data
x(x<182) = NaN;
这些事情通常可以通过逻辑索引来完成:
A = randn(1,100);
B = randn(size(A));
test = (A>1|A<0); % For example, values that are greater than 1 or less than 0
A(test) = B(test);
或另一个例子:
A = randn(1,100);
test = (A>1|A<0);
A(test) = randn(1,nnz(test));
或其他:
A = randn(1,100);
A(A>1|A<0) = NaN;
您可以像这样使用循环:
for i = 1:length(matrix(:,1))
for j = 1:length(matrix(1,:))
if matrix(i,j) < 182
matrix(i,j) = NaN;
end
end
end