Is the Zeroes Function here necessary?

조회 수: 1 (최근 30일)
Andew
Andew 2018년 2월 21일
댓글: Stephen23 2018년 2월 21일
Here is the code:
nuclei=zeros(1,100);
t=nuclei;
nuclei(1)=input('Enter initial number of nuclei: ');
t(1)=0;
t_c=input('Enter time constant: ');
dt=input('Time step: ');
for i=1:99
nuclei(i+1)=nuclei(i)-(nuclei(i)/t_c)*dt;
t(i+1)=t(i)+dt;
end
plot(t,nuclei,'-ok','MarkerFaceColor','k')
xlabel('Number of Nuclei','FontWeight','bold')
ylabel('time(s)','FontWeight','bold')
title('Radioactive Decay Number of nuclei versus time')
str1=['Time Constant= ' num2str(t_c) ' s '];
str2=['Time Step= ' num2str(dt) ' s'];
text(t(50),nuclei(10),str1,'FontWeight','bold','FontSize',14)
text(t(50),nuclei(20),str2,'FontWeight','bold','FontSize',14)
I have plots that result from this code, and this code with that first line removed, and they appear to be the same. Is that first line necessary? If so, why?
  댓글 수: 1
Stephen23
Stephen23 2018년 2월 21일
No code is "necessary".
In this situation zeros makes that code much more efficient: array preallocation means that MATLAB does not waste time moving data around in memory:

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

채택된 답변

Greg
Greg 2018년 2월 21일
It's called pre-allocation. It is always a good idea to pre-allocate. If you need a quick proof, throw a tic / toc around the code with and without the zeros line. It'll get noticeably faster as the number of loop iterations grows.
  댓글 수: 2
Andew
Andew 2018년 2월 21일
thanks!
Greg
Greg 2018년 2월 21일
Happy to help.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by