필터 지우기
필터 지우기

Problems With Function Error

조회 수: 2 (최근 30일)
John Woods
John Woods 2020년 6월 3일
댓글: Walter Roberson 2020년 6월 3일
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
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
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
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 CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by