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
댓글 수: 0
답변 (1개)
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]);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!