vectorizing or speeding looped code

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

답변 (1개)

Turlough Hughes
Turlough Hughes 2020년 9월 22일

0 개 추천

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

Paul Schenk
Paul Schenk 2020년 9월 22일
the dimensions change (get smaller) in each of the 4 runs. they will have to be declared each time.
Turlough Hughes
Turlough Hughes 2020년 9월 22일
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
Paul Schenk 2020년 9월 22일
이동: Rik 2026년 2월 4일 13:57
not as entered. tripled cpu time.
here are preallo's to variables:
ORDER_MAX = 20;
C = zeros(ORDER_MAX+1,1);
IORD=MAXOR;
IORD1=IORD+1;
B = single(zeros(ORDER_MAX+1,ORDER_MAX+1)); % Solution matrix
XP = double(zeros(ORDER_MAX+1,1)); % Array of solutions
Paul Schenk
Paul Schenk 2020년 9월 22일
이동: Rik 2026년 2월 4일 13:57
a1 and a2 are linear (1,2000) arrays that are usually only 10% filled in.
Turlough Hughes
Turlough Hughes 2020년 9월 23일
이동: Rik 2026년 2월 4일 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
Paul Schenk 2020년 9월 23일
이동: Rik 2026년 2월 4일 13:58
hope this works for you. it is essentially a customized LS fit solution.
Turlough Hughes
Turlough Hughes 2020년 9월 23일
이동: Rik 2026년 2월 4일 13:58
Can you give some typical inputs aswell?
Paul Schenk
Paul Schenk 2020년 9월 23일
이동: Rik 2026년 2월 4일 13:58
example:
eqor=1, n=222 and a1 and a2 are linear vectors of numbers N long (they change each time and can be random for this test)
Turlough Hughes
Turlough Hughes 2020년 9월 23일
이동: Rik 2026년 2월 4일 13:58
eqor=1 ? I assume that's MAXOR?
Paul Schenk
Paul Schenk 2020년 9월 23일
이동: Rik 2026년 2월 4일 13:58
yes, my mistake!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

질문:

2020년 9월 22일

이동:

Rik
2026년 2월 4일 13:58

Community Treasure Hunt

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

Start Hunting!

Translated by