Reputation: 309
I have one column matrix as follows
P = [1;2];
I Have another column matrix Q
which has to be added to the first matrix. But the number of rows in second column matrix is always more than that of P
Q = [4;5;6];
i want to split or reshape Q
according to size of P
. if size of P
is n
, then first n
elements of Q
goes into the second column of output and the remaining elements to third coulmn while the first column of output is nothing but P
I need the output as below but I cannot use the reshape as I am not sure of the size of both matrices as they can vary.
output = [1 4 6;2 5 0];
Could someone assist me?
Thanks
Upvotes: 1
Views: 177
Reputation: 1797
You can also append the required number of zeros within the reshape
statement itself, resulting in a single line solution
R = [P reshape([Q; zeros(numel(P) - mod(numel(Q),numel(P)),1)],numel(P),[])]
Upvotes: 1
Reputation:
% 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
This will work for any size of P
and Q
if they are both initially vectors (not matrices)
Upvotes: 2
Reputation: 112679
If you have the Communications Toolbox, use vec2mat
:
result = vec2mat([P(:); Q(:)], numel(P)).';
Upvotes: 2