Problems With Function Error
4 ビュー (過去 30 日間)
古いコメントを表示
I am just trying to understand how these functions work so I took a sample equation from my notes and tried to use matlab to solve it. This is my code:
g=9.81;
m=156;
cd=0.25;
disp(vt);
function vt= doodle(g,m,cd,t)
vt=sqrt((g*m)/cd)*tanh(sqrt((g*c)/m)*t);
end
I have saved the file as doodle.m and it gives me an error that says "Error: File: doodle.m Line: 5 Column: 14
Function 'doodle' has already been declared within this
scope."
What am I not doing right?
1 件のコメント
BN
2020 年 6 月 3 日
Hi, Your answer is in this link I think. They say you should not start function with g=9.81. Try start it in other way. Good luck
回答 (1 件)
Peter O
2020 年 6 月 3 日
Up until recently, MATLAB had a requirement to separate scripts from functions. A file could hold one but not both types. Now, it can hold both, but functions must appear at the bottom so that it can distinguish the script parts from the function declarations.
A script is the top four lines of your code. It calls the disp() function with the argument vt. MATLAB will throw an error here because as it goes line-by-line, it discovers that vt has not yet been assigned a value.
A function is the next three, it contains the declaration term FUNCTION, the outputs, the name of the function, and the arguments to it (in parentheses). Scope determines when a variable is alive and active -- anything available to the function must be in its argument list. It need not match the script part. For instance, a variable called z in the script can be called v in the function.
To do anything interesting, you need to call the function from the script part.
z = 2;
newval = add_five(z);
disp(newval) % prints '7'
function vp5 = add_five(v)
vp5 = v + 5;
end
Try this on for size. Note also that I'm using the elementwise multiplication operator .* to apply the operation across the entire array.
g=9.81;
m=156;
cd=0.25;
t = linspace(0,1,100); % Declare an array of times
vt = doodle(g,m,cd,t);
plot(t,vt)
xlabel('Time')
ylabel('Vt')
function vt= doodle(g,m,cd,t)
vt=sqrt((g*m)/cd)*tanh(sqrt((g*cd)/m).*t);
end
1 件のコメント
Walter Roberson
2020 年 6 月 3 日
This description is correct, but does not quite address the cause of the error message.
When you define a function inside a script, the name of the function must be different than the name of the script.
It is (since R2016b) valid to have a function inside a script but the names must be different from each other.
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!