フィルターのクリア

How do you call local functions?

18 ビュー (過去 30 日間)
Caroline F
Caroline F 2022 年 4 月 9 日
回答済み: Caroline F 2022 年 4 月 9 日
Hi! I am learning about local functions and I am not sure how to use them with a script. I am trying to make a function with only one input (radius) and two outputs (surface area and volume) for a sphere. I am suppossed to test it with when the radius = pi and have the two outputs. So far I have this and I keep getting an area about matlab being out of memory due to an infinite incursion within the program.
clc
clear all
r(pi)
function radius = r(x)
SA = 4*pi*r^.2;
V = (4/3)*pi*r^.3;
end
  1 件のコメント
Stephen23
Stephen23 2022 年 4 月 9 日
編集済み: Stephen23 2022 年 4 月 9 日
There is no problem with how you are calling the local function.
However there are several basic problems with the function itself:
function radius = r(x) % you do not use variable x anywhere in your function
SA = 4*pi*r^.2; % variable r is undefined, r is a recursive function call
V = (4/3)*pi*r^.3; % variable r is undefined, r is a recursive function call
radius = ??? % You need to define the output variable
end
The main problem is that you think you are using a variable r, but in fact you are calling the function recursively.
Note that both SA and V are completely unused. I strongly recommend that you avoid using one-letter function names.

サインインしてコメントする。

採用された回答

Caroline F
Caroline F 2022 年 4 月 9 日
I figured it out. Thank you to everyone who responded for your help!
sphere_prop(pi) ;
function [SA,V] = sphere_prop(r)
SA = 4*pi*r^2
V = (4/3)*pi*r^3
end

その他の回答 (1 件)

KSSV
KSSV 2022 年 4 月 9 日
編集済み: KSSV 2022 年 4 月 9 日
function radius = r(x)
SA = 4*pi*r^.2;
V = (4/3)*pi*r^.3;
end
Save the above function inti a file r.m. (I suggest bigger name). Go the folder where this file is present/ or addpath of the function. Now call the function.
x = 1 ;
radius = r(x) ;
Or, you can copy it in a file and run the code.
clc; clear all ;
radius = r(2) ;
function radius = r(x)
SA = 4*pi*r^.2;
V = (4/3)*pi*r^.3;
end
Give different name to the function. If you name a variable with 'r' your function cannot be called.

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by