Effacer les filtres
Effacer les filtres

How do you call local functions?

18 vues (au cours des 30 derniers jours)
Caroline F
Caroline F le 9 Avr 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 commentaire
Stephen23
Stephen23 le 9 Avr 2022
Modifié(e) : Stephen23 le 9 Avr 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.

Connectez-vous pour commenter.

Réponse acceptée

Caroline F
Caroline F le 9 Avr 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

Plus de réponses (1)

KSSV
KSSV le 9 Avr 2022
Modifié(e) : KSSV le 9 Avr 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.

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by