How do I use nargin to differentiate between a default units setting and unit input from function call

I'm still very new to MATLAB. I need to be able to call my function and if no units are input then it defaults to 'm' like so:
figure(1)
ellipsoid_volume(8,17,'Volume versus Depth for an Ellipsoid')
Otherwise I need to be able to insert the correct units in my function like so:
figure(1)
ellipsoid_volume(8,17,'Volume versus Depth for an Ellipsoid','cm')
How do I use nargin to do this? My homework specifically states, "Use the nargin command to verify the proper number of input arguments and assign units = 'm' if no units are provided."
function ellipsoid_volume(a,b,plot_title,units)
% ellipsoid_volume
% James R. Wallace, JR.
% 30 August 2019
%
% Calculates volume of horizontal ellipsoid and plots data
% Inputs:
% a - vertical semi-axis
% b - horizontal radius
% plot_title - string holding plot title
% units - optional string describing units, default = 'm'
units = 'm'; % Default units is meters
h = 0:(3*a); % Initializing h(height) to index from zero to 3 times a
% Calculating volume of liquid in horizontal ellipsoid
V = (pi/3).*(3*a-h).*((b.^2*h.^2)/a.^2);
% Plotting
yOut = ['Volume [',units,'^3]'];
xOut = ['Depth [',units,']'];
plot(h,V)
ylabel(yOut)
xlabel(xOut)
title(plot_title)

 採用された回答

Stephen23
Stephen23 2019 年 8 月 30 日
編集済み: Stephen23 2019 年 8 月 30 日
Replace
units = 'm';
with
if nargin<4
units = 'm';
end

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB Report Generator についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by