0

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)

  • 2
    Loops are not inherently slow in MATLAB, sometimes they can be a way to optimise memory usage and therefore run things faster - for instance you don't create as many intermediate variables or call as many different functions with the loop. You're comparing sub-millisecond runtimes, this would be better tested with large inputs, and `timeit()`. Can you give a sense of how big your real inputs are? – Wolfie Jan 18 '23 at 13:39
  • @Wolfie this is a part of the code using "Anderson acceleration" method, I changed the existing code in order to find a set of solutions in one call – Nekkache Abdesslem Jan 18 '23 at 15:05
  • 2
    20-some years ago, loops in MATLAB were quite slow, but this is no longer true. But people are still frantically trying to eliminate loops from their code for no good reason. Please don’t do this, just use your original code with the loop, you are unlikely to make it faster. – Cris Luengo Jan 18 '23 at 15:08

0 Answers0