How can I create and call a simple user defined function?
조회 수: 696 (최근 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
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
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
2019년 7월 24일
편집: Stephen23
2019년 7월 24일
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
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개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!