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

1 visualización (últimos 30 días)
Kevin Kleiboemer
Kevin Kleiboemer el 25 de Mayo de 2021
Editada: Jan el 25 de Mayo de 2021
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

Respuestas (1)

Jan
Jan el 25 de Mayo de 2021
Editada: Jan el 25 de Mayo de 2021
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]);

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by