フィルターのクリア

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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by