Use a structure as input in a function

17 Ansichten (letzte 30 Tage)
Stian Olsen
Stian Olsen am 22 Mär. 2019
Kommentiert: Steven Lord am 12 Okt. 2020
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 :/

Antworten (1)

Stephan
Stephan am 22 Mär. 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 Kommentare
Ashlianne Sharma
Ashlianne Sharma am 12 Okt. 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
Steven Lord am 12 Okt. 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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Elementary Polygons finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by