I would like to speed up my code and avoid for loops. I want to extract smaller matrices which are placed along the diagonal of a bigger matrix and put those into an array. The code looks like this:
SC = zeros(m, n, n);
for i = 1:m
SC(i, 1:n, 1:n) = matrix(n*(i-1)+1:i*n, n*(i-1)+1:i*n);
end
SC = SC(:,:,:);
Do I have to include the for loop or is there a way to extract the matrix all at once?

 채택된 답변

Matt J
Matt J 2020년 6월 7일
편집: Matt J 2020년 6월 7일

0 개 추천

First, your code should be faster if SC is nxnxm as opposed to mxnxn. That will make the memory accesses more contiguous. Assumig you accept this, then the following is a loop-free way to build SC.
B=repmat({sparse(true(n))},1,m);
idx=blkdiag(B{:});
SC=reshape( matrix(idx) ,n,n,[]);

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2020a

질문:

2020년 6월 7일

편집:

2020년 6월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by