Sparse matrix from the columns of an initial square matrix
1 view (last 30 days)
Show older comments
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.
4 Comments
Matt J
on 1 Nov 2022
Edited: Matt J
on 1 Nov 2022
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
Accepted Answer
Bruno Luong
on 1 Nov 2022
n=3;m=2;
A=randi(10,n,m) % m columns are used; not n
J=(1:m*n);
I=mod(J-1,n)+1;
B = sparse(I, J, A)
C = full(B) % if full is prefered
0 Comments
More Answers (0)
See Also
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!