Variable Usage in Function File
조회 수: 5 (최근 30일)
이전 댓글 표시
Unfortunately, I still am not very knowledgeable about using "function" commands in Matlab. As such, I have two questions.
1) In this short script, I want to save vel() so I can plot it at the end. But when the script completes, the variable workspace is wiped clean; thus vel() is gone. How can I retain this variable after script completion?
function vend=velocity1(dt, ti,tf,vi)
t=ti;
v=vi;
n=(tf-ti)/dt;
for i=1:n
dvdt=deriv(v);
v=v+dvdt*dt;
vel(i,1)=v;
end
vend=v;
end
function dv=deriv(v)
dv=9.81-(0.25/68.1)*v^2;
end
2) With the same script above, why does the software give me an error if I add a prefix to it as shown in the following? These input variables need defined, so I'm not sure why the software would give an error.
dt=0.5;
ti=0;
tf=12;
vi=0;
function vend=velocity1(dt, ti,tf,vi)
.
.
.
<same script as above>
Thanks in advance, M Ridzon
댓글 수: 0
채택된 답변
James Tursa
2017년 9월 21일
편집: James Tursa
2017년 9월 21일
1) Return vel as an output of your function. E.g.,
function [vel,vend] = velocity1(dt, ti,tf,vi)
2) Have your driver code and function code in separate files. E.g.,
% A file called velocity1_driver.m (or some other name of your choosing)
dt = 0.5;
ti = 0;
tf = 12;
vi = 0;
[vel,vend] = velocity1(dt, ti, tf, vi);
:
etc
And then a function file
% A file called velocity1.m
function [vel, vend] = velocity1(dt,ti,tf,vi)
:
etc
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!