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

조회 수: 2 (최근 30일)
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 ?

답변 (2개)

dpb
dpb 2023년 1월 18일
편집: dpb 2023년 1월 18일
"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 2023년 1월 18일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by