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
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by