Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are isscalar, isvector and ismatrix all true for A = 1?

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 matrix

For 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?

like image 399
Schorsch Avatar asked Aug 29 '14 20:08

Schorsch


Video Answer


2 Answers

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:

  • A scalar is considered to be a 1x1 matrix
  • An n-vector is just a 1 x n or n x 1 matrix
  • 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.

like image 148
Luis Mendo Avatar answered Oct 25 '22 02:10

Luis Mendo


Because Matlab interprets scalars as 1-by-1 arrays, see the size documentation.


Therefore, depending on your application, you would have to

  • use isscalar to distinguish a vector from a scalar (because it will return false for a vector)
  • use 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.

like image 37
Schorsch Avatar answered Oct 25 '22 02:10

Schorsch