How to assume values on an input vector

1 view (last 30 days)
Im trying to make a function with a single input vector that contains 4 values. If the user inputs a vector with 3 numbers, the function should assume the 4th to be the 3rd value + 5, and so on with only 2 values, etc.
Using isempty(x(4)) causes an error due to the vector not containing a 4th value, so I am not sure how to detect the number of inputs in the vector
if isempty(x(4)) && isempty(x(3)) && isempty(x(2))
disp('Error: Scalor values not accepted')
  1 Comment
Stephen23
Stephen23 on 8 Oct 2018
Edited: Stephen23 on 8 Oct 2018
if isempty(x(4)) && isempty(x(3)) && isempty(x(2))
Your statement and your code show some confusion about arrays, which will make using MATLAB difficult. Any single element of an array accessed using parentheses, e.g. x(4), by definition has size 1x1 and will never be empty. So none of those tests are useful. You should simply be testing for the size of the complete array, or the number of elements in the array (as my answer shows), or possibly the sizes of the contents of some container variable.
"...so I am not sure how to detect the number of inputs in the vector"
A vector does not have any "number of inputs", so this statement does not relate to anything in MATLAB. A vector itself might be an input argument to a function. A vector, like any other array, has zero or more elements, the number of which is determined by its size. This has nothing to do with any "inputs" (whatever that means).
Basic concepts that you need to know to use MATLAB (such as what vectors/arrays are and how they are made up of elements), are explained in the introductory tutorials:

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 8 Oct 2018
Edited: Stephen23 on 8 Oct 2018
Use numel to measure how many elements the input vector has, something like this:
function myfun(X)
assert(isvector(x),'input must be a vector')
switch numel(X)
case 1
... your code
case 2
... your code
case 3
... your code
case 4
... your code
otherwise
???
end
Note that there would be simple ways to achieve this, using indexing. Basic indexing is also explained in the introductory tutorials.

More Answers (0)

Categories

Find more on Programming 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!