Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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 comentarios
Stephen23
Stephen23 el 6 de Ag. de 2018
Editada: Stephen23 el 6 de Ag. de 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 el 6 de Ag. de 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.

Iniciar sesión para comentar.

Respuestas (1)

Jos (10584)
Jos (10584) el 6 de Ag. de 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)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by