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

DGM
DGM 2021년 11월 9일
편집: DGM 2021년 11월 9일
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
tot = 122
% alternatively
T = eye(3);
vec_1 = [4,5,6];
vec_2 = [7,8,9];
tot = sum(T .* vec_1.' .* vec_2,'all')
tot = 122
If T is always an identity matrix, then it simplifies further
tot = vec_1*vec_2.'
tot = 122

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

질문:

2021년 11월 9일

댓글:

2021년 11월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by