How to test function inputs for vector/scalar?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2023-2-13
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!