フィルターのクリア

How to avoid linear indexing in operations involving matrices of different sizes

2 ビュー (過去 30 日間)
deathtime
deathtime 2023 年 5 月 5 日
編集済み: Matt J 2023 年 5 月 5 日
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(:)
C = 6×1
1.5283 1.5581 1.0464 1.4741 0.5704 0.2374
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.

採用された回答

Stephen23
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
C = 3×2
1.6889 0.4419 0.7161 0.1917 1.4049 0.7527

その他の回答 (1 件)

Matt J
Matt J 2023 年 5 月 5 日
編集済み: Matt J 2023 年 5 月 5 日
A = rand(3,3);
B = rand(3,2);
idx = logical([0 1 1; 0 1 1; 0 1 1]);
C=B;
C(:)=A(idx)+B(:)
C = 3×2
1.1539 0.5087 1.1585 1.0807 1.4266 0.7590

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by