필터 지우기
필터 지우기

Is there a way to create such type of "block diagonal' matrix without loop?

조회 수: 1 (최근 30일)
YU BAI
YU BAI 2018년 8월 6일
답변: Jos (10584) 2018년 8월 6일
Hello,guys! I have a question. Suppose I have a matrix like this:
A=[1 2 3;
4 5 6]
I would like to transform this matrix to B which takes this form:
B=[0 0 0;
1 0 0;
0 1 2;
0 0 0;
4 0 0;
0 4 5].
I have the code which allocate the non-zero elements to B with loop.
E=zeros(6,3);
count_E=0;
for i=1:2
E(i+1:3:end,count_E+1:count_E+i) = A(:,1:i);
count_E = count_E+jj;
end
Is there a better way to do it without loop? Thanks! In practice this A matrix is very large which means that B contains lots of zeros. I am thinking of use sparse matrix. However, to index sparse matrix within the loop seems to be time consuming.
  댓글 수: 2
Stephen23
Stephen23 2018년 8월 6일
편집: Stephen23 2018년 8월 6일
@YU BAI: please explain the logic that converts A into B, because there is no one clear pattern:
A=[1 2 3;
4 5 6]
B=[0 0 0;
1 0 0;
0 1 2;
0 0 0;
4 0 0;
0 4 5].
YU BAI
YU BAI 2018년 8월 6일
Hi, This is a step used for Bayesian VAR analysis with stochastic volatility. You can look at section 8.3. for details. http://joshuachan.org/notes_BayesMacro.html. The question I mentioned is about draw the elements in L: the correlation matrix. I would say that Joshua's code is almost perfect but I am thinking if there is a way to further improve it, since the E matrix has a kind of "diagonal" structure.

댓글을 달려면 로그인하십시오.

답변 (1개)

Jos (10584)
Jos (10584) 2018년 8월 6일
A = [ 1 2 3 ;
4 5 6 ]
B = arrayfun(@(k) sparse([2 3 3],[1 2 3],A(k,[1 1 2])),1:size(A,1),'un',0)
B = cat(1,B{:})
full(B)

카테고리

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