从某一行开始按列替换值

Replace values from a certain row onwards column-wise

我有一个10x5双矩阵mat。我还有一个 1x5 行向量 start_rows。在 mat 中,我想使用 start_rows 替换特定行中的所有数字。我可以使用循环并逐列替换所有数字。但是,我确定有一些矢量化解决方案。

mat = nan(10, 5);
start_rows = [3,5,1,7,2];

% How to avoid that loop
for idx = 1 : numel(start_rows)
    mat(start_rows(idx):end, idx) = 1;
end

这可以通过将以下形式的数组与您的 start_rows 向量进行比较来解决:

     1     1     1     1     1
     2     2     2     2     2
     3     3     3     3     3
     4     4     4     4     4
     5     5     5     5     5
     6     6     6     6     6
     7     7     7     7     7
     8     8     8     8     8
     9     9     9     9     9
    10    10    10    10    10

这将 return 满足条件时的逻辑数组(这使用广播 AKA 隐式扩展)。


如果 mat 始终包含零,而您要替换为一:

(1:size(mat,1)).'+ mat >= start_rows;

如果 mat 非零:

(1:size(mat,1)).'+ 0*mat >= start_rows;             % option 1
(1:size(mat,1)).'+ zeros(size(mat)) >= start_rows;  % option 2

如果替换为 1(或 true)以外的值:

((1:size(mat,1)).'+ 0*mat >= start_rows) * newVal;