MATLAB – 使用条件编辑矩阵的一部分

huangapple go评论73阅读模式
英文:

MATLAB - Editing a portion of a matrix with conditions

问题

我知道使用条件编辑矩阵可以这样做:

X = [1 1 0 0; 
     0 0 1 1; 
     1 0 1 0; 
     0 0 1 0]

X(X==0) = 1

我想仅对矩阵的下半部分应用条件更改,我尝试过这样做:

X(3:4,1:4)(X==0) = 1;

但会返回错误:“错误:无效的数组索引。”

英文:

I know that editing a matrix with conditions is done this way:

X = [1 1 0 0; 
     0 0 1 1; 
     1 0 1 0; 
     0 0 1 0]

X(X==0) = 1

I want to apply the conditional changes only to the lower half of the matrix and I've tried doing this.

X(3:4,1:4)(X==0) = 1;

But an error is returned: "Error: Invalid array indexing."

答案1

得分: 3

你的逻辑索引条件是 X==0

你可以修改这个逻辑索引,使得你不想修改的部分为假。

idx = (X==0);       % 条件
idx(1:2,:) = false; % 不修改行1-2的元素
X( idx ) = 1;       % 根据idx为真的元素修改数组

如果你愿意,你可以在一行中定义 idx,尽管这可能不太清晰。

idx = (X==0) & ((1:size(X,1)).' >= 3); % 定义包括行号 >= 3 的条件
X( idx ) = 1;
英文:

Your logical indexing condition is X==0.

You can modify this logical index such that the half you don't want to modify is false.

idx = (X==0);       % condition
idx(1:2,:) = false; % don't modify rows 1-2 with this index
X( idx ) = 1;       % modify the array according to elements where idx is true

You can define idx in one line if you want, although this is probably less clear

idx = (X==0) & ((1:size(X,1)).' >= 3); % define condition including row number >= 3
X( idx ) = 1; 

huangapple
  • 本文由 发表于 2023年7月12日 20:34:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定