将向量v
组合到矩阵A
中的最有效方法是什么,如下所示? (不使用for循环)。
输入:
v = [1;2;3;4;5;6;7;8;9]
所需的输出矩阵:
A =
1 0 0
2 0 0
3 0 0
0 4 0
0 5 0
0 6 0
0 0 7
0 0 8
0 0 9
答案 0 :(得分:1)
这是一种方法:创建一个零矩阵,然后定义一个linear index,其中包含将写入向量值的位置:
v = [1;2;3;4;5;6;7;8;9]; %// data vector
n = 3; %// group size
N = numel(v);
A = zeros(N, N/n); %// define A filled with zeros
A(bsxfun(@plus, reshape((1:N).',n,[]), (ceil(1:N/n)-1)*N)) = v; %'// fill in v with
%// linear indexing
此示例中的结果:
A =
1 0 0
2 0 0
3 0 0
0 4 0
0 5 0
0 6 0
0 0 7
0 0 8
0 0 9
答案 1 :(得分:1)
使用零填充和重新整形的一种方法 -
m = 3; %// To select group of "m" elements from v for each col in o/p
N = numel(v); %// Number of elements in input vector
%// Reshape, pad with zeros
vpad = [reshape(v,m,[]) ; zeros(N,N/m)]
%// Clip off at "N*N/m" elements and reshape into 2D array with N rows
A = reshape(vpad(1:N*N/m),N,[])
示例运行 -
v =
31 19 46 82 57 10 36 5 46 39 90 74
m =
4
A =
31 0 0
19 0 0
46 0 0
82 0 0
0 57 0
0 10 0
0 36 0
0 5 0
0 0 46
0 0 39
0 0 90
0 0 74