Sparse matrix from the columns of an initial matrix

조회 수: 1 (최근 30일)
POHL Michel
POHL Michel 2021년 4월 5일
답변: Bjorn Gustavsson 2021년 4월 5일
Hello everyone, given a matrix A of size (m,n),
I would like to construct a matrix B of size (m,m*n) the following way :
for j = 1:n
col_start = (j-1)*m+1;
col_end = j*m;
B(:,col_start:col_end) = diag(A(:,j));
end
This version uses a for loop, is there any faster way of constructing B?
Thank you in advance.

답변 (1개)

Bjorn Gustavsson
Bjorn Gustavsson 2021년 4월 5일
Something like this might work:
vals = [];
idx1 = [];
idx2 = [];
for j = 1:n
idx1 = [idx1,1:n];
col_start = (j-1)*m+1;
col_end = j*m;
idx2 = [idx2,col_start:col_end];
vals = [vals,A(:,j)'];
end
B2 = sparse(idx1,idx2,vals);
For optimal speed-improvements pre-allocate vals, idx1 and idx2 and assign those with indices instead of growing these arrays.
HTH

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by