Use a structure as input in a function
18 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Im looking to make a function that takes a structure containing the radius and height of several cylinders ad calculates the volume and surface area.
Can i use the whole structure as one input, and if so, how do i access it?
The structre would be called 'cylinder' with the classes: 'radius' and 'height'.
If I call the input parameter in the function 'x' woud i then access it with x(1).heigt? I cant get it to work :/
0 Commenti
Risposte (1)
Stephan
il 22 Mar 2019
Hi,
try:
% Define cylinder 1
cylinder(1).radius = 2;
cylinder(1).height = 1.5;
% Define cylinder 2
cylinder(2).radius = 4;
cylinder(2).height = 5;
% Call the function
[volume, surface_area] = cylinder_calc(cylinder)
% Function that calculates surface and volume from the given structs
function [volume, surface_area] = cylinder_calc(cylinder)
volume = pi.*cell2mat({cylinder.radius}).^2 .* cell2mat({cylinder.height});
surface_area = 2*pi.*cell2mat({cylinder.radius}).*...
(cell2mat({cylinder.radius}) + cell2mat({cylinder.height}));
end
Best regards
Stephan
2 Commenti
Ashlianne Sharma
il 12 Ott 2020
Hi Stephan,
So to my understanding, you use the structure as the variable and specify what variable within the stucture is going to be used. Because there are two different sets of cylinder values, you leave the generic cylinder structure in the function? Along with this, when you put in your command window (in this example) you would type [volume, surface_area] you would get the two values. When you do this, do you have to specify what structure you want your values to come from?
Kindest regards,
Ashlianne
Steven Lord
il 12 Ott 2020
You can do this with cell2mat but a simpler approach would be to use a for loop.
% Define cylinder 1
cylinder(1).radius = 2;
cylinder(1).height = 1.5;
% Define cylinder 2
cylinder(2).radius = 4;
cylinder(2).height = 5;
% Call the function
[volume, surface_area] = cylinder_calc(cylinder);
% Function that calculates surface and volume from the given structs
function [volume, surface_area] = cylinder_calc(cylinder)
% Preallocate the outputs
volume = zeros(size(cylinder));
surface_area = zeros(size(cylinder));
for whichCylinder = 1:numel(cylinder)
% Save some typing by pulling the cylinder's data into a shorter variable name
C = cylinder(whichCylinder);
volume(whichCylinder) = pi*C.radius.^2 * C.height;
% Similar for surface_area
end
Vedere anche
Categorie
Scopri di più su Elementary Polygons in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!