Variable Usage in Function File

5 ビュー (過去 30 日間)
Matthew
Matthew 2017 年 9 月 21 日
編集済み: James Tursa 2017 年 9 月 21 日
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 Center および File ExchangeIntroduction 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