How do you call local functions?

19 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Surface 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