Divide a matrix with an array along a specific dimension

15 visualizaciones (últimos 30 días)
ANKUR KUMAR
ANKUR KUMAR el 16 de Mzo. de 2018
Comentada: Beata Opacka el 26 de Mzo. de 2020
A=rand(10,20,30);
B=[1:30];
I want to divide A with B along the third dimension. I got the required result using loop.
for ii=1:30
C(:,:,ii)=A(:,:,ii)/B(ii);
end
But is there any pre-defined function which does the same operation, which takes the dimension as a input along which we want to divide a matrix.

Respuesta aceptada

Stephen23
Stephen23 el 16 de Mzo. de 2018
Editada: Stephen23 el 16 de Mzo. de 2018
Once you make the sizes compatible you can do this using standard methods without any loop. Use permute or reshape to get the correct size of B. For example In R2016b and later a standard rdivide will do this:
A ./ reshape(B,1,1,[])
or for earlier versions use bsxfun:
bsxfun(@rdivide,A,reshape(B,1,1,[]))

Más respuestas (1)

Akira Agata
Akira Agata el 16 de Mzo. de 2018
How about using arrayfun ?
C = arrayfun(@(k) A(:,:,k)./B(k), 1:30,'UniformOutput',false);
C = cat(3,C{:});

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by