How can I create a matrix from a vector with the vector indices given in a matrix, without using a loop?

1 回表示 (過去 30 日間)
Dear all,
I have a (1x6) vector v and would like to create a (5x5) matrix A from the vector entries of v. Another (5x5) matrix B demonstrates the pattern. I would like to create A such that A(i,j)=v(1,B(i,j)) if B(i,j)>0 and A(i,j)=0 if B(i,j)=0.
B=[2 3 4 5 6; 3 4 5 6 0; 4 5 6 0 0; 5 6 0 0 0; 6 0 0 0 0]
I know how to do that in a loop, but since I have to do this operation on a large scale, I am looking for an efficient way to do this in vectorized form. It might be related to a more efficient (generalized) way of defining B, but I can't find the solution.
I would very much appreciate any help, thanks in advance!

採用された回答

Distelfink
Distelfink 2022 年 3 月 3 日
The easiest way to go is the command hankel(v(2:6)). See the answer I received in this thread

その他の回答 (1 件)

Benjamin Thompson
Benjamin Thompson 2022 年 3 月 3 日
編集済み: Benjamin Thompson 2022 年 3 月 3 日
If you can add an entry to v to handle the creating of the zero entries in A, it can be pretty elegant. First make A as a vector and then call reshape to convert to 5x5:
>> B=[2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 7; 5 6 7 7 7; 6 7 7 7 7]
B =
2 3 4 5 6
3 4 5 6 7
4 5 6 7 7
5 6 7 7 7
6 7 7 7 7
>> v = [1 2 3 4 5 6 0]'
v =
1
2
3
4
5
6
0
>> A = v(B(:))
A =
2
3
4
5
6
3
4
5
6
0
4
5
6
0
0
5
6
0
0
0
6
0
0
0
0
>> A = reshape(A,5,5)'
A =
2 3 4 5 6
3 4 5 6 0
4 5 6 0 0
5 6 0 0 0
6 0 0 0 0
  2 件のコメント
Distelfink
Distelfink 2022 年 3 月 3 日
That works well, Benjamin, thank you very much! Just one thing, you have the line A = reshape(A,5,5)' twice in your answer; the first should be deleted.
Benjamin Thompson
Benjamin Thompson 2022 年 3 月 3 日
I have corrected that, and thanks for accepting the answer!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by