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

1 次查看(过去 30 天)
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