我有一个列矩阵如下
P = [1;2];
我有另一个列矩阵Q
,必须将其添加到第一个矩阵中。但是第二列矩阵中的行数总是多于P
Q = [4;5;6];
我想根据Q
的大小拆分或重塑P
。如果P
的大小为n
,则n
的第一个Q
元素将进入第二列输出,其余元素将转换为第三列,而第一列输出为除了P
我需要输出如下,但我不能使用重塑,因为我不确定两个矩阵的大小,因为它们可以变化。
output = [1 4 6;2 5 0];
有人可以帮助我吗?
由于
答案 0 :(得分:2)
如果您有通讯工具箱,请使用vec2mat
:
result = vec2mat([P(:); Q(:)], numel(P)).';
答案 1 :(得分:2)
% first we fill Q with appropiate number of zeros
% (basically we see how many times Q is bigger than P rounded up)
new_Q = zeros(numel(P)*ceil(numel(Q)/numel(P)), 1);
new_Q(1:numel(Q)) = Q;
% then we create a new matrix containing `P` and the reshaped `new_Q`
R = [P reshape(new_Q, [numel(P), numel(new_Q)/numel(P)])]
R =
1 4 6
2 5 0
如果它们都是最初的向量(不是矩阵),这适用于任何大小的P
和Q
答案 2 :(得分:2)
您还可以在reshape
语句中附加所需数量的零,从而产生单行解决方案
R = [P reshape([Q; zeros(numel(P) - mod(numel(Q),numel(P)),1)],numel(P),[])]