我想通过根据为每行指定的列索引执行操作来逐行减少矩阵中的列数。给出以下示例数据:
M = magic(4);
col_ind = [1; 3; 2; 4];
我想制作一个三列矩阵,这样第一列包含每行到指定列索引的行和,第二列包含该行中M
的值,由列索引,最后一列包含该行中其余条目的行和,即生成矩阵M_out
:
M_out = nan(4,3);
for i = 1:4
M_out(i, :) = [sum(M(i, 1:col_ind(i)-1), 2), ...
M(i, col_ind(i)), sum(M(i, col_ind(i)+1:end), 2)];
end
这样:
>> M_out
M_out =
0 16 18
16 10 8
9 7 18
33 1 0
答案 0 :(得分:3)
根据Stewie's comment,我将使用tril
在此处执行此操作。第二列使用sub2ind
很简单。然后第三列变得微不足道了:
T = tril(ones(size(M, 2)), -1);
M_out = zeros(size(M, 1), 3);
M_out(:, 1) = sum(T(col_ind,:) .* M, 2);
M_out(:, 2) = M(sub2ind(size(M), (1:size(M, 1)).', col_ind));
M_out(:, 3) = sum(M, 2) - sum(M_out, 2);
或者,使用cumsum
提高效率:
cs = cumsum(M, 2);
M_out = zeros(size(M, 1), 3);
M_out(:, 2) = M(sub2ind(size(M), (1:size(M, 1)).', col_ind));
M_out(:, 1) = cs(sub2ind(size(cs), (1:size(cs, 1)).', col_ind)) - M_out(:, 2);
M_out(:, 3) = cs(:, end) - sum(M_out, 2);