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 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