英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论