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

采纳的回答

James Tursa
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 个)

类别

Help CenterFile 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!

Translated by