Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
YU BAI
YU BAI am 6 Aug. 2018
Beantwortet: Jos (10584) am 6 Aug. 2018
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 Kommentare
Stephen23
Stephen23 am 6 Aug. 2018
Bearbeitet: Stephen23 am 6 Aug. 2018
@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 am 6 Aug. 2018
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jos (10584)
Jos (10584) am 6 Aug. 2018
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)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by