How to make non iterative code faster than the iterative when using line by line backslash inverse ?
1 次查看(过去 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)
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)
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 ?
0 个评论
回答(2 个)
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.
0 个评论
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!