Problems With Function Error

4 vues (au cours des 30 derniers jours)
John Woods
John Woods le 3 Juin 2020
Commenté : Walter Roberson le 3 Juin 2020
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 commentaire
BN
BN le 3 Juin 2020
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

Connectez-vous pour commenter.

Réponses (1)

Peter O
Peter O le 3 Juin 2020
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 commentaire
Walter Roberson
Walter Roberson le 3 Juin 2020
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by