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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by