Sparse matrix from the columns of an initial square matrix

Hello everyone, given a matrix A of size (n,n),
I would like to construct a matrix B of size (n,m*n) the following way:
B = zeros(n,m*n);
for j = 1:m
col_start = (j-1)*n+1;
col_end = j*n;
B(:,col_start:col_end) = diag(A(:,j));
end
This version uses a for loop, is there any faster way of constructing B?
The difficulty for me is to achieve the same result without a for loop. I precised "sparse" in the summary, but I do not necessarily refer to the sparse matrix data type in Matlab; B is sparse in a mathematical sense.
Thank you in advance.
PS: I asked a similar question last year, but in this question, A is assumed to be a square matrix.

4 Comments

Did you try to initialize B? Why do you think the present loop is slow?
I have just edited the question to include the initialization of B in the code snipped. I think that there might be a faster way to accomplish that. For instance, if all columns of A were identical, I would use the repmat function, which is faster than a brutal implementation with a for loop.
You haven't shown us what the output should be. Here is what I get when I run your code with some input data. Is this correct?
n=3;m=2;
A=rand(n);
B = zeros(n,m*n);
for j = 1:m
col_start = (j-1)*n+1;
col_end = j*n;
B(:,col_start:col_end) = diag(A(:,j));
end
A,B
A = 3×3
0.7619 0.2149 0.5172 0.2228 0.1111 0.0854 0.6459 0.4688 0.1326
B = 3×6
0.7619 0 0 0.2149 0 0 0 0.2228 0 0 0.1111 0 0 0 0.6459 0 0 0.4688
Ah yes, you understood my question well, thank you for your contribution!

Sign in to comment.

 Accepted Answer

n=3;m=2;
A=randi(10,n,m) % m columns are used; not n
A = 3×2
7 10 2 2 2 9
J=(1:m*n);
I=mod(J-1,n)+1;
B = sparse(I, J, A)
B =
(1,1) 7 (2,2) 2 (3,3) 2 (1,4) 10 (2,5) 2 (3,6) 9
C = full(B) % if full is prefered
C = 3×6
7 0 0 10 0 0 0 2 0 0 2 0 0 0 2 0 0 9

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!