For my engineering class I had to make a while loop to find the average of a data set and use tic/toc to time the process. My code is posted below but for some reason when I run tic/toc it says it takes 7 seconds. I'm just not sure this is right because a few of my classmates told me theirs was around 1 second and when I time it myself it doesn't take 7 seconds. If someone could tell me where my error is if there is one I would appreciate it!

댓글 수: 4

sorry here is my code!
y=load('ClassSDPprep_watts.txt');
tic;
sum=0;
i=1;
while i<=length(y);
sum=sum+y(i);
i=i+1;
end
Average
time=toc
Walter Roberson
Walter Roberson 2017년 10월 29일
We recommend against using a variable named "sum", as it is almost certain that at some point you will have a variable with that name at at time that you want to use the sum() function.
Walter Roberson
Walter Roberson 2017년 10월 29일
편집: Walter Roberson 2017년 10월 29일
You have not given us any information about what Average does.
You could improve your performance by calculating length(y) once before the loop and using that variable. With your current code it needs to recalculate length(y) every step.
Amanda Wojcik
Amanda Wojcik 2017년 10월 29일
Ok thank you that makes sense! When I copied the code I forgot to include average=sum/length(y)

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

답변 (0개)

카테고리

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

질문:

2017년 10월 29일

댓글:

2017년 10월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by