Matlab中的无环子矩阵分配

时间:2015-10-24 21:21:02

标签: matlab matrix vectorization matrix-indexing submatrix

我的大小为F的矩阵D-by-NA范围内随机整数长度为N的向量[1,a]。我想创建一个大小为M的矩阵D * a,以便每个列M(:,i)都具有从索引F(:,i)(A(i)-1)*D+1的向量(A(i)-1)*D+D

示例:

F = [1 2 3 10
     4 5 6 22]

A = [3 2 1 2]

a = 4

M = [0 0 3 0
     0 0 6 0
     0 2 0 10
     0 5 0 22
     1 0 0 0
     4 0 0 0
     0 0 0 0
     0 0 0 0]

我可以通过简单的循环

来完成
        for i = 1 : N
            M((A(i)-1)*D+1:(A(i)-1)*D+D,i) = F(:,i);
        end

但对于大型N,这可能需要一段时间。我正在寻找一种无需循环的方法。

1 个答案:

答案 0 :(得分:2)

您可以将bsxfun用于基于linear-indexing的方法 -

[D,N] = size(F);    %// Get size of F

start_idx = (A-1)*D+1 + [0:N-1]*D*a;          %// column start linear indices
all_idx = bsxfun(@plus,start_idx,[0:D-1]');   %//'# all linear indices

out = zeros(D*a,N); %// Initialize output array with zeros
out(all_idx) = F;   %// Insert values from F into output array

示例运行 -

F =
     1     2     3    10
     4     5     6    22
A =
     3     2     1     2
a =
     4
out =
     0     0     3     0
     0     0     6     0
     0     2     0    10
     0     5     0    22
     1     0     0     0
     4     0     0     0
     0     0     0     0
     0     0     0     0