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?
CodePudding user response:
If T is always the identity matrix, then you are only looking at the trace of the outer product, which is just the inner product:
tot = vec_1 * vec_2'
If T could be arbitrary and not always the identity matrix, you could just code the outer product directly:
tot = sum(T.*(vec_1'*vec_2),'all')
CodePudding user response:
You can easily do it by the following code:
M = vec1 .* T; % multiply all rows element-wise by vec1
N = vec2.' .* T; % multiply all columns element-wise by vec1
result = (M.*N); % multiply element-wise M to N
tot = sum(result, 'all');