I have three algorithms to calculate the inner product of vector
A(i,j) and vector V for M x N times.
With the line A = round(A), B1 = B2 = B3.
Without the line A = round(A);, B1 != B2, B2 = B3.
Is this a precision error?
Which one is correct?
clc;100
clear all;
M = 1000;
N = 1000;
P = 10;
A = 10*rand(M,N,P);
A = round(A);
% A = zeros(M,N,P);
% for i = 1:P
% A(:,:,i) = i;
% end
V = 1:P;
% Algorithm 1
A = shiftdim(A,2);
tic;
B1 = zeros(M,N);
for i = 1:M
for j = 1:N
B1(i,j) = V*A(:,i,j);
end
end
t1 = toc;
A = shiftdim(A,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Algorithm 2
tic;
temp = zeros(M,N,P);
for i = 1:P
temp(:,:,i) = A(:,:,i)*V(i);
end
B2 = sum(temp,3);
clear temp;
t2 = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Algorithm 3
tic
v = repmat(reshape(V, [1 1 P]), [M N]);
temp = bsxfun(@times, A, v);
B3 = sum(temp,3);
clear temp;
t3 = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
isequal(B1,B2,B3)
isequal(B1,B2)
isequal(B2,B3)
isequal(B1,B3)
t1
t2
t3
