Add / subtract / multiply / divide matrix by vector along defined dimension

1 回表示 (過去 30 日間)
Kevin Kleiboemer
Kevin Kleiboemer 2021 年 5 月 25 日
編集済み: Jan 2021 年 5 月 25 日
Hi,
I have a matrix A with the size [5 11 4 11] and a vector B with the size [4]. I want to divide the matrix by the vector by the third dimension of the matrix, in a way, that
for i = 1:4
C(:,:,i,:) = A(:,:,i,:) / B(i);
end
The same I want with subtracting. Is there a better, predefined way, than using a loop? Preferaed would be a function, which has the dimension as a parameter, such as
Example: C = divdim(A,B,3);
Thank you

回答 (1 件)

Jan
Jan 2021 年 5 月 25 日
編集済み: Jan 2021 年 5 月 25 日
A = rand([5, 11, 4, 11]);
B = rand([4, 1]); % Or [1, 4]? "[4]" is no valid size in Matlab
C = A ./ reshape(B, [1, 1, 4, 1]); % Note: ./ , not /
D = A - reshape(B, [1, 1, 4, 1]);
...
This works since R2016b, when the auto-expanding was introduced. With older Matlab versions you need bsxfun.
You can omit the trailing 1's in the dimension, so this is sufficient already:
E = A + reshape(B, [1, 1, 4]);

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by