Use a structure as input in a function
조회 수: 17 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Stephan
2019년 3월 22일
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
Ashlianne Sharma
2020년 10월 12일
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
2020년 10월 12일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Elementary Polygons에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!