How to multiply values to specific elements in a matrix?
조회 수: 16 (최근 30일)
이전 댓글 표시
I have a matrix
A=[ 1 0 0 0;
0 1 0 0;
1 0 0 0;
0 0 0 1 ]
I want to multiply an array B= [1,5,7,8] to wherever 1's are in matrix A. Resultant matrix is:
A = [1 0 0 0;
0 5 0 0 ;
7 0 0 0;
0 0 0 8]
How can I do it in vectorized form? Please note that number of ones in input matrix A will always equal the length of array B
Thanks!
댓글 수: 0
답변 (2개)
the cyclist
2016년 11월 19일
편집: the cyclist
2016년 11월 19일
In MATLAB 2016b (and presumably later yet-to-be-released versions), you can just write
A.*B'
In earlier versions, you need to use bsxfun:
bsxfun(@times,A,B')
댓글 수: 0
Roger Stafford
2016년 11월 20일
Assuming the number of ones in A is equal to the length of B,
At = A.’;
At(At==1) = B;
A = At.’;
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!