Sparse matrix from the columns of an initial square matrix
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
KSSV
on 1 Nov 2022
Did you try to initialize B? Why do you think the present loop is slow?
Michel Pohl
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
Michel Pohl
on 12 Nov 2022
Accepted Answer
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!