How to make non iterative code faster than the iterative when using line by line backslash inverse?

43 Views Asked by At

This code creats a matrix B contains the product of the each line of A by the backslash inverse of a aline of x

A = [1,2,3,8,1;10,45,7,3,1;9,8,15,75,65,];
x = [14,5,11,15,33;7,1,9,1,1;87,45,11,0,65]; 
B=zeros(3,1);
% the iterative code
tic
for k = 1:size(x,1)
B(k) = A(k,:)*(x(k,:)\1);
end
t1 = toc;
disp(B)

How do I avoid the for loop, and keep the code faster?

I notice that, in MATLAB, the backslash of a vector x returns a vector y which inverse the maximum element and make the rest 0,the I tried to make the code without for loop:

tic
% code without iteration
ind = x==max(abs(x),[],2);
y = (1./x).*ind; 
y(isnan(y))=0;
C = sum(A.*y,2);
t2 = toc;
disp(C)

I got the same output. However, the second code was slower in my pc than the first code t1 = 0.000681. t2 = 0.002536 . I tried the pinv() function but it doesn't give the same results (the backslash inverse is better for my code)

0

There are 0 best solutions below