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!