How to resize a matrix with zeros in between elements

Hello everyone.
I have matrix A and I would like to obtain matrix B.
I have used C(:,1:2)=diag(A(1,:)) but I do not know how to do it automatically because I need to use this code for a bigger matrix.
A =
10 5
4 10
2 3
B =
10 0 4 0 2 0
0 5 0 10 0 3

 Accepted Answer

Some general solutions for matrix A of any size.
>> A = [10,5;4,10;2,3];
Method one: sub2ind:
>> [R,C] = size(A);
>> B = zeros(C,R*C);
>> B(sub2ind(size(B),1+mod(0:R*C-1,C),1:R*C)) = A.'
B =
10 0 4 0 2 0
0 5 0 10 0 3
Method two: reshape:
>> [R,C] = size(A);
>> B = reshape([reshape(A.',1,[]);zeros(C,C*R)],[],R);
>> B = reshape(B(1:end-C,:),C,[])
B =
10 0 4 0 2 0
0 5 0 10 0 3
Method three: linear indexing:
>> [R,C] = size(A);
>> B = zeros((1+C)*C,R);
>> B(1:C+1:end-C) = A.';
>> B = reshape(B(1:end-C,:),C,[])
B =
10 0 4 0 2 0
0 5 0 10 0 3
Method four: blkdiag:
>> B = cell2mat(cellfun(@(c)blkdiag(c{:}),num2cell(num2cell(A),2),'uni',0).')
B =
10 0 4 0 2 0
0 5 0 10 0 3

3 Comments

Thank you. Method four is great!
@Daniel Aguirre: My pleasure. The fourth is probably also the slowest.
@madhan ravi: Thank you!

Sign in to comment.

More Answers (1)

Try this - will work for any size of A:
A =[...
10 5
4 10
2 3];
[m,n] = size(A);
B = zeros(n,(2*m+n)-2);
c = (1:2:2*m).' + (0:n-1); % use bsxfun(@plus,(1:2:2*m).', 0:n-1) if your using version <= 2016a
r = repmat(1:n,size(c,1),1);
B(sub2ind(size(B),r,c)) = A
Gives:
B =
10 0 4 0 2 0
0 5 0 10 0 3
The below is given according to the assumption that A has n no of rows but only 2 columns, B has only 2 rows and n no of rows.
B = zeros(size(A,2),2*size(A,1));
B(1,1:2:end) = A(:,1);
B(2,2:2:end) = A(:,2)

Categories

Asked:

on 24 Jul 2019

Edited:

on 24 Jul 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!