필터 지우기
필터 지우기

Vectorizing Code - how can I populate elements of a matrix from a vector without a FOR loop?

조회 수: 2 (최근 30일)
I need to populate a large matrix from elements of a vector without using a FOR loop. The sizes of my vector and matrix can be quite large but the problem has the form of this shortened version:
a = [a1 a2 a3]
B = [a1 a1 0 0 0 0;...
a1 a1 0 0 0 0;...
0 0 a2 a2 0 0;...
0 0 a2 a2 0 0;...
0 0 0 0 a3 a3;...
0 0 0 0 a3 a3]
This is for a time simulation where the elements of "a" change every time step. The form of "B" does not change, only the elements from "a".
Again, this is easily done with a FOR loop, but in the interest of speed, I really need to avoid using loops here. I'm hoping there is a simple answer but for now, I'm stumped.
Thoughts and suggestions please!
Cheers,
- Eric

답변 (3개)

Fangjun Jiang
Fangjun Jiang 2011년 9월 26일
a=[1 2 3];
B=arrayfun(@(x) x*ones(2),a,'uni',0);
B=blkdiag(B{:})

Jan
Jan 2011년 9월 26일
a = rand(1, 3);
B = kron(diag(a), ones(2));

David Holdaway
David Holdaway 2012년 5월 29일
Do you NEED to make B as a matrix? Fangjun Jiang and Jan Simon's methods will work fine for what you have asked, but I've found if your vectors get big the ordinary "*" multiplication in Matlab is not very efficient for large block-diagonal matrices and it takes masses of memory to store and you are better off looping over the blocks anyway. (This is assuming there are no clever inbuilt tools in Matlab for block diagonal matrices I have never heard of).

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by