Matlab has the following functions to check inputs:
isscalar
to determine whether input is scalar isvector
to determine whether input is a vector ismatrix
to determine whether input is a matrixFor A = 1
(or any "scalar" input) all of the above return true
.
Why do I see this counter-intuitive behavior?
And how would I indentify A = 1
as scalar?
I don't find it counter-intuitive at all. In Mathematics there exist vectors of 1 dimension (even though they are isomorphic with scalars). Also, a matrix can perfectly have size 1x1.
It is true that a single number could be considered a scalar, a 1-vector or a 1x1 matrix. Matlab's view is:
More generally: trailing singleton dimensions don't count. For example, a 3D-array of size 2x3x4 can also be considered, say, a 5D-array of size 2x3x4x1x1. This works without error:
>> a = rand(2,3,4);
>> a(2,2,2)
ans =
0.2575
>> a(2,2,2,1,1)
ans =
0.2575
Now, if you want to check if A
is a vector, matrix, or multidimensional array with more than one element, use
numel(A)>1
The numel
function returns the number of elements of its input argument.
Because Matlab interprets scalars as 1-by-1 arrays, see the size
documentation.
Therefore, depending on your application, you would have to
isscalar
to distinguish a vector from a scalar (because it will return false
for a vector)isvector
to distinguish a matrix from a vector (because it will return false
for a matrix)Because if you are trying to figure out if a variable is a vector and not a scalar and you use isvector
, both a scalar and a vector will return true
- as pointed out in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With