I've made a script (Triangle.m) to calculate the area of a triangle in MATLAB:
function Triangle()
% Main function
clc;
clear variables;
close all;
% Set function values
base = force_positive_finite("Base");
height = force_positive_finite("Height");
area = tri_area(base,height);
fprintf("Area: %2.3f m²\n",area);
end
function output = force_positive_finite(var_name)
% Ask/force the user to enter a positive number
output = -1;
while true
output = input("Enter in "+var_name+" (m): ");
if input_error_response(output)
% If no error, leave loop
break
end
end
end
function response = input_error_response(in)
% Warns user if input is invalid
if isempty(in) || in < 0 || in==inf % Value must be a non-empty positive number
disp("Enter a value: {0 <= VALUE < inf}");
response = false; % This signals the loop to continue
else
response = true; % This means we can exit the loop
end
end
function area = tri_area(base,height)
% Calculate the area of a triangle
arguments
base {mustBeNumeric, mustBeFinite};
height {mustBeNumeric, mustBeFinite};
end
area = base*height*0.5;
end
It contains force_positive_finite to ensure the input is >= 0 and finite, then is fed into tri_area where it is checked to be numeric and finite, before calculating the area.
I am new to MATLAB, so any pointers on convention, optimisation and general improvements are appreicated.
input()interaction is usually something you want to confine to the very top-level application, and keep it out of utility functions. \$\endgroup\$clc, thank you \$\endgroup\$