1

我有一个F大小矩阵和一个范围内随机整数长度的D-by-N向量。我想创建一个大小矩阵,使得每个列都有从索引开始的向量。AN[1,a]MD * aM(:,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这可能需要一段时间。我正在寻找一种没有循环的方法。

4

1 回答 1

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
于 2015-10-24T21:44:29.110 回答