How do you call local functions?

67 visualizzazioni (ultimi 30 giorni)
Caroline F
Caroline F il 9 Apr 2022
Risposto: Caroline F il 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 Commento
Stephen23
Stephen23 il 9 Apr 2022
Modificato: Stephen23 il 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.

Accedi per commentare.

Risposta accettata

Caroline F
Caroline F il 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

Più risposte (1)

KSSV
KSSV il 9 Apr 2022
Modificato: KSSV il 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.

Categorie

Scopri di più su Mathematics and Optimization in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by