How to test function inputs for vector/scalar?
조회 수: 2 (최근 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!