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

2 views (last 30 days)
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!

Accepted Answer

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

More Answers (1)

Benjamin Thompson
Benjamin Thompson on 3 Mar 2022
Edited: Benjamin Thompson on 3 Mar 2022
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!