vectorizing or speeding looped code
Show older comments
i am trying to speed up some code with multiple functions and have found the one that takes the most time (it is all a converted fortran code). it runs a nested for loop 4 times (each with modified input). i've had some success elsewhere in the code eliminating slow points but this one just cant get right. any ideas? (in 2016b for compatability reasons)
for II= 1:N
XP(1)= 1.0D0;
for JJ=2:IORD1
XP(JJ)=XP(JJ-1)*double(A1(II));
end
for JJ= 1:IORD1
for KK= 1:IORD1
B(JJ,KK)=B(JJ,KK)+XP(JJ)*XP(KK);
end
C(JJ)=C(JJ)+XP(JJ)*A2(II);
end
end
Answers (1)
Turlough Hughes
on 22 Sep 2020
This should help, though I've already made assumptions about the sizes of arrays. How many rows/columns are in each variable?
XP(1) = 1;
for II= 1:N
XP(2:end) = XP(1:end-1)*double(A1(II));
B = B + XP(:).*XP(:).';
C = C + XP*A2(II);
end
10 Comments
Paul Schenk
on 22 Sep 2020
Turlough Hughes
on 22 Sep 2020
Did the code work?
Some questions: is XP a column vector/row vector? Does A2 have as many elements as XP? Also, does B contain IORD1 rows and columns? Similarly does C have IORD1 elements?
Paul Schenk
on 22 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:57
Paul Schenk
on 22 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:57
Turlough Hughes
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:57
Vectorisation is usually faster but not always. Probably best to just provide a minimum working example (google it) of code that I (or others) can test and profile. Otherwise it really is just guess work.
Paul Schenk
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:58
Turlough Hughes
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:58
Can you give some typical inputs aswell?
Paul Schenk
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:58
Turlough Hughes
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:58
eqor=1 ? I assume that's MAXOR?
Paul Schenk
on 23 Sep 2020
Moved: Rik
on 4 Feb 2026 at 13:58
Categories
Find more on Descriptive Statistics and Visualization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!