我正在寻找在指定行R
之前将多行M
插入矩阵I
的最有效方法,同时将现有行向下移动。
M = [1 1 1 1;
2 2 2 2;
3 3 3 3;
4 4 4 4;
5 5 5 5];
I = [1 3 3 5];
R = [-6 -6 -6 -6;
-7 -7 -7 -7;
-8 -8 -8 -8
-9 -9 -9 -9];
结果应该是矩阵:
[-6 -6 -6 -6
1 1 1 1
2 2 2 2
-7 -7 -7 -7
-8 -8 -8 -8
3 3 3 3
4 4 4 4
-9 -9 -9 -9
5 5 5 5]
答案 0 :(得分:5)
此功能在file exchange上提供。它本质上的作用是:
ind = [1:size(M, 1) I-1];
[~, ind] = sort(ind);
MR = [M; R];
MR = MR(ind,:);
答案 1 :(得分:2)
以下内容可行,但我认为只有I
中的索引按递增顺序排序(如果不是,您可以先添加一些排序步骤)。无论如何,我会用“真实”数据测试它:
[m,n] = size(M);
l = length(I);
MM = zeros(m+l,n);
MM(I+(1:l)-1,:) = R; % I+(1:l)-1 are the row indices of the final matrix in which to insert the the rows of R
MM(~ismember(1:(l+m),I+(1:l)-1),:) = M; % ~ismember(...) are the other row indices (using logical indexing)
这给出了:
>> MM
MM =
-6 -6 -6 -6
1 1 1 1
2 2 2 2
-7 -7 -7 -7
-8 -8 -8 -8
3 3 3 3
4 4 4 4
-9 -9 -9 -9
5 5 5 5
答案 2 :(得分:2)
这可能是一种方法 -
R_rowind = cumsum([I(1) diff(I)+1]) %// Row indices where rows from R are
%// to be inserted in the output matrix
rowidx_arr = 1:size(M,1)+size(R,1) %// array of [1 : number_of_rows_in_output]
out(setdiff(rowidx_arr,R_rowind),:) = M %// Insert rows from M into output array
out(R_rowind,:) = R %// Insert rows from R into output array
请注意,对于从M插入行到输出数组,您可以使用基于bsxfun
的替代方法 -
out(all(bsxfun(@ne,rowidx_arr,R_rowind'),1),:) = M