How can I create and call a simple user defined function?
133 ビュー (過去 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 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!