Vectorization not working in Matlab - Matrix dimensions do no agree?
Show older comments
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 Comment
Stephen23
on 9 Nov 2021
As DGM shows, you need to replace T(m,n) with T.
Answers (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.'
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!