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!
댓글 수: 0
채택된 답변
추가 답변 (1개)
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!