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

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by