How can I create and call a simple user defined function?
938 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Carlos
el 20 de Ag. de 2013
Comentada: ihsan ghafoor
el 13 de Oct. de 2023
I am trying to teach myself MATLAB with a book but I am having problems creating and calling user defined functions. Here is the code I used for area of a circle exactly as it is in the book:
function area= calcarea(rad)
%calcarea calculates the area of a circle
%Format of call: calcarea(radius)
%Returns the area
area=pi*rad*rad; <----------Error in this line
end
When I run it. It says Error using calcarea line 6 Not Enough Input Arguments
1 comentario
ihsan ghafoor
el 13 de Oct. de 2023
you dont have to run that file.
just write in the command window
calcarea(45)
and it will give the answer.
Never run the function file, always check it by writing the function name in command window with suitable inputs.
Respuesta aceptada
Image Analyst
el 20 de Ag. de 2013
You'd have to run that from a script or the command line and supply an argument for rad. Or you can put it in a function called test.m like this
function test
% Call calcarea
theArea = calcarea(42);
function area= calcarea(rad)
%calcarea calculates the area of a circle
%Format of call: calcarea(radius)
%Returns the area
area = pi * rad * rad;
Note, in the above you can have them both in the same m-file, but you must have the "function test()" in there because otherwise you'd have a script followed by the calcarea function and you can't mix a script and a function in the same file, but you can mix two functions in the same file.
3 comentarios
Stephen23
el 24 de Jul. de 2019
Editada: Stephen23
el 24 de Jul. de 2019
function area=calcarea(rad)
rad=input('enter the value of radius=')
...
No, you definitely should not, because then you make the input argument rad completely useless. Using input is an awful way to provide data to a function, input arguments (exactly like the original question and answer show) are much better.
John D'Errico
el 30 de Mzo. de 2023
@Suryabhan Singh please don't add answers asking another question, even if it is semi-related to the original question.
If you are having problems, first, don't name a function with the same name as a script is is called within.
As for your subsequent problems, it is difficult to answer that, without actually seeing what you did.
I would STRONGLY suggest you spend some time reading the MATLAB Onramp tutorial.
Even after that, if you get an error, then you need to show the ENTIRE error, so everything in red. That helps us to track down what you are doing wrong. My guess is, you may not undestand the difference between a function and a script, but that is just a wild guess. So show what you wrote, and what error you got, the complete error message.
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!