function that calculates the area of geometrical shapes in matlab

main.m
function area = calculate_area(shape, varargin)
    if strcmp(shape, 'rectangle')
        area = varargin{1} * varargin{2};
    elseif strcmp(shape, 'circle')
        area = pi * varargin{1}^2;
    elseif strcmp(shape, 'triangle')
        area = 0.5 * varargin{1} * varargin{2};
    else
        error('Invalid shape provided');
    end
end
341 chars
12 lines

This function named calculate_area takes in the shape of the geometrical figure as a string (e.g., 'rectangle', 'circle', 'triangle') as the first argument, and then a variable number of arguments depending on the shape. For a rectangle, it takes two side lengths, for a circle it takes the radius, and for a triangle it takes the base and height. It calculates and returns the respective area based on the shape and input parameters.

related categories

gistlibby LogSnag