Vectorization not working in Matlab - Matrix dimensions do no agree?
이전 댓글 표시
I want to multiply elements of a matrix T against elements of two vectors vec_1 and vec_2, and sum everything up. Using nested for loops, I can do it like this:
T = eye(3);
vec_1 = [4,5,6];
vec_2 = [7,8,9];
tot = 0;
for m=1:3
for n=1:3
tot = tot + T(m,n) .* vec_1(m) .* vec_2(n);
end
end
I wanted to make it faster using vectorization so I tried the following.
T = eye(3);
vec_1 = [4,5,6];
vec_2 = [7,8,9];
f = @(m,n) T(m,n) .* vec_1(m) .* vec_2(n);
[M, N] = meshgrid(1:3,1:3);
tot = sum(f(M,N),'all');
However, this doesn't work and I get the error 'Matrix dimensions must agree.' From debugging it, the problem is due to T being evaluated using M and N. Instead of returning a 3x3 matrix as I expected, T(M,N) returns a 9x9 matrix. How can I fix this code so I can use vectorization instead of nested for loops for this task?
댓글 수: 1
Stephen23
2021년 11월 9일
As DGM shows, you need to replace T(m,n) with T.
답변 (1개)
It can be simpler than that.
% original
T = eye(3);
vec_1 = [4,5,6];
vec_2 = [7,8,9];
tot = 0;
for m=1:3
for n=1:3
tot = tot + T(m,n) .* vec_1(m) .* vec_2(n);
end
end
tot
% alternatively
T = eye(3);
vec_1 = [4,5,6];
vec_2 = [7,8,9];
tot = sum(T .* vec_1.' .* vec_2,'all')
If T is always an identity matrix, then it simplifies further
tot = vec_1*vec_2.'
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!