Clear Filters
Clear Filters

How do you call local functions?

48 views (last 30 days)
Caroline F
Caroline F on 9 Apr 2022
Answered: Caroline F on 9 Apr 2022
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 Comment
Stephen23
Stephen23 on 9 Apr 2022
Edited: Stephen23 on 9 Apr 2022
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.

Sign in to comment.

Accepted Answer

Caroline F
Caroline F on 9 Apr 2022
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

More Answers (1)

KSSV
KSSV on 9 Apr 2022
Edited: KSSV on 9 Apr 2022
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.

Categories

Find more on Mathematics and Optimization in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!