How can I create and call a simple user defined function?

826 次查看(过去 30 天)
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 个评论
ihsan ghafoor
ihsan ghafoor 2023-10-13
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.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2013-8-20
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 个评论
Stephen23
Stephen23 2019-7-24
编辑:Stephen23 2019-7-24
srinivas chappa wrote: "you should assign the value to rad."
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
John D'Errico 2023-3-30
@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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by