I am looking to optimize the following code specifically, and more generally, I am trying to learn optimization techniques in MATLAB for a larger project. The code below is just a snippet example which I am looking to learn techniques and then apply to a larger problem. I am potentially looking at values of L being as high as with four nested loops as opposed to just the two shown below.
Any pointers (or links to decent YouTube video on MATLAB optimization) would be welcomed.
clc; clearvars;
T = 1; Ts = 1e-2; t = 0:Ts:L*T;
L = 2^5;
start_time = clock();
for l = 0:L-1
for q = 0:L-1
flag = (t>=(l-q-1)*T) & (t<=(l-q+1)*T);
partA = (T-abs(t-(l-q)*T));
end
end
elapsed_time = clock();
time = elapsed_time(4)*3600+elapsed_time(5)*60+elapsed_time(6)

댓글 수: 4

for q = 0:L-1
flag = (t>=(l-q-1)*T) & (t<=(l-q+1)*T);
It looks to me as if you should see discretize and possibly splitapply
Catalytic
Catalytic 2022년 11월 20일
@Howard Wilton You appear to have opened several previous threads on similar subjects to this and abandoned them, without accepting an answer or follow-up discussion. It is better if you not do this, so that contributors can know if the question is to be taken seriously.
Howard Wilton
Howard Wilton 2022년 11월 20일
The questions didn't really hit the answer so i thought i would cast the questions differently.
However, your advice is duly noted and i shall be careful in the future. Thanks.
Howard Wilton
Howard Wilton 2022년 11월 20일
편집: Howard Wilton 2022년 11월 20일
I have taken the code a bit further and managed to dispense with the nested loops . However, I still need a 1D loop. Performance is substantially improved.
clc; clearvars;
L = 2^8; T = 1; t = 0:0.2:L*T;
start_time = clock();
l = 1:L; q = 1:L;
X = (l(:)-q(:).')*T;
for loop = 1:length(t)
t2(:,:,loop) = t(loop) - X;
end
stop_time = elapsedTime(start_time)
function time = elapsedTime(start_time)
elapsed_time = clock-start_time;
time = elapsed_time(4)*3600+elapsed_time(5)*60+elapsed_time(6);
end
Keen to figure out a way to eliminate the 1D loop and generate a matrix .

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

 채택된 답변

Walter Roberson
Walter Roberson 2022년 11월 20일

0 개 추천

X = (l(:)-q(:).')*T;
for loop = 1:length(t)
t2(:,:,loop) = t(loop) - X;
end
replace with
t2 = reshape(t, 1, 1, []) - X;

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2020b

질문:

2022년 11월 20일

댓글:

2022년 11월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by