MATLAB: Help using sub functions

functionsMATLABnested functionsub function

I need to use the values calculated in the 3 subfunctions.
The 3 sub functions each calculate a surface area. The goal for the main function is to use the 3 surace areas and multiply them by a price and output the 3 prices. The 3 sub functions use the same volume from the main function. I am not sure how to complete this task. Help is appreciated!
I am required to use local/subfunctions or else I would have calculated all of the SAs to be indidividual variables.
function Options= NV_hw2_4(volume,cost) %goal here is to use the surface areas from the subfunctions and multiply them by the price which will be an input in the main function
SAS= [cubeSA,cylinderSA,sphereSA]
Options= price.*SAS
function cubeSA= getSA1(volume) %this function finds the surface area of a cube based on volume
g=nthroot(volume,3) %solving for the side length and assigning it to g
cubeSA=6*g^2 % calculating surface area based off the side length (g)
end
function cylinderSA= getSA2(volume) %this finds SA of the cylinder based on volume
c= nthroot((volume/pi),3) %finding the radius required
cylinderSA= (2*pi*c^2)*2 %calculating surface area with the required radius to match the desired volume
end
function sphereSA= getSA3(volume) %this funds the SA of the sphere
d= nthroot((volume/((4/3)*pi)),3) %solving for the required radius
sphereSA= (4*pi*d^2)%calculating the surface area with the required radius for the desired volume
end
end

Best Answer

function Options=NV_hw2_4(volume,price) %goal here is to use the surface areas from the subfunctions and multiply them by the price which will be an input in the main function
cubeSA= getSA1(volume) ;
cylinderSA= getSA2(volume) ;
sphereSA= getSA3(volume) ;
SAS= [cubeSA,cylinderSA,sphereSA] ;
Options= price.*SAS
end
function cubeSA= getSA1(volume) %this function finds the surface area of a cube based on volume
g=nthroot(volume,3) %solving for the side length and assigning it to g
cubeSA=6*g^2 % calculating surface area based off the side length (g)
end
function cylinderSA= getSA2(volume) %this finds SA of the cylinder based on volume
c= nthroot((volume/pi),3) %finding the radius required
cylinderSA= (2*pi*c^2)*2 %calculating surface area with the required radius to match the desired volume
end
function sphereSA= getSA3(volume) %this funds the SA of the sphere
d= nthroot((volume/((4/3)*pi)),3) %solving for the required radius
sphereSA= (4*pi*d^2)%calculating the surface area with the required radius for the desired volume
end
Run like this:
volume = 10 ;
price = 5 ;
options = NV_hw2_4(volume,price) ;
Related Question