How to test function inputs for vector/scalar?
1 view (last 30 days)
Show older comments
I am coding for an assignment in which I have a function. The function has 3 inputs. The first two inputs need to be combined in a single vector for their input, and the other input is a scalar. The first thing my function needs to do is test if the inputs are in the correct format (the first 2 inputs being in a single vector and the third input being a scalar). I would prefer to use an IF statement to do this test, so how does one test for wether the inputs are the correct format?
For a bit of background, here is my function definition
function [wire_length,spring_mass] = spring_length_mass([inner_diameter outer_diameter],number_coils)
it would then go into the IF statement to test for proper input format.
0 Comments
Accepted Answer
Voss
on 13 Feb 2023
You cannot concatenate things in a function definition like this:
function [wire_length,spring_mass] = spring_length_mass([inner_diameter outer_diameter],number_coils)
% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't do this here
Instead make those two variables a single input (say, diameters) in the function definition and then separate them (if you must) after you check that diameters has two elements:
function [wire_length,spring_mass] = spring_length_mass(diameters,number_coils)
if numel(diameters) == 2
inner_diameter = diameters(1);
outer_diameter = diameters(2);
else
error('Incorrect number of diameters given.')
end
if ~isscalar(number_coils)
error('number_coils must be a scalar.')
end
% ... calculation of wire_length and spring_mass ...
end
Note that this allows diameters to be a 3D (or higher dimensional) array, which is not a vector, as long as it has 2 elements, such as diameters=rand(1,1,2). If you really want to constrain diameters to be a 1-by-2 vector or a 2-by-1 vector, you can use isvector.
You may also need/want to check that the correct number of inputs is given, for which you can use nargin.
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!