How to avoid linear indexing in operations involving matrices of different sizes
1 次查看(过去 30 天)
显示 更早的评论
If I carry out an operation of matrices with different sizes using indexing, the end result tends to be a column matrix with linear indexing. For example:
A = rand(3,3);
B = rand(3,2);
idx = logical([0 1 1; 0 1 1; 0 1 1]);
If I want to add A with idx indices to B, the only way I can seem to make this work is if I do:
C = A(idx) + B(:)
Is there any way to carry out the above operation and end up with a matrix the same shape as B? My initial attempt was to simply do C = A(idx) + B.
0 个评论
采纳的回答
Stephen23
2023-5-5
RESHAPE is very efficient, because no data gets moved in memory:
A = rand(3,3);
B = rand(3,2);
idx = logical([0,1,1;0,1,1;0,1,1]);
C = reshape(A(idx),size(B)) + B
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!