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

3 views (last 30 days)
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
disp(B)
0.0303 0.7778 0.1034
t1 = toc;
I tried to make the code without for loop:
tic
% code without iteration
ind = x==max(abs(x),[],2);
y = (x.\1);
z = y.*ind;
z(isnan(z))=0;
C = sum(A.*z,2);
disp(C)
0.0303 0.7778 0.1034
t2 = toc;
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)
Is there any other solution ?

Answers (2)

dpb
dpb on 18 Jan 2023
Edited: dpb on 18 Jan 2023
"Is there any other solution ?"
Yeah, go on to the next step in your overall problem.
There's nothing wrong with for...end loops when they're the simpler coding solution.
You had to introduce a bunch of other stuff and temporary variables to eliminate the straightforward loop construct and as the timing shows, MATLAB does a good job with loops with the JIT optimizer and when the output array is pre-allocated.

MJFcoNaN
MJFcoNaN on 18 Jan 2023
Hello,
The example may not show that iterative one is faster, because they are both too simple and fast.
I will suggest you try a more complicate case for example by enlarging the matix, at the same time, Matlab provides "run and time" option which will give out details of every line's efficiency.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!