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

Matlab performs the following functions for checking inputs:

  • isscalar to determine if an input is scalar
  • isvector to determine if an input is a vector
  • ismatrix to determine if an input matrix

For A = 1 (or any "scalar" input), all of the above returns true .
Why do I see this anti-intuitive behavior?
And how would I define A = 1 as a scalar?

+5
source share
2 answers

I do not find this completely intuitive. In mathematics, there are vectors of 1 dimension (although they are isomorphic to scalars). In addition, the matrix may have a size of 1x1.

It is true that one number can be considered a scalar, 1-vector or 1x1-matrix. View Matlab:

  • The scalar is considered a 1x1 matrix
  • An n-vector is just 1 xn or nx 1 matrix
  • More generally: the long sizes of a singleton are not taken into account. For example, a 3D array of size 2x3x4 can also be considered, for example, a 5D array of size 2x3x4x1x1. This works without errors:

     >> 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 vector, matrix, or multidimensional array with more than one element , use

 numel(A)>1 

The numel function returns the number of elements of the input argument.

+5
source

Since Matlab interprets scalars as 1-on-1 arrays see size documentation.


Therefore, depending on your application, you should

  • use isscalar to distinguish a vector from a scalar (because it will return false for the vector)
  • use isvector to distinguish a matrix from a vector (because it will return false for the matrix)

Because if you are trying to figure out if a variable is a vector, not a scalar, and you use isvector , both the scalar and the vector return true - as indicated in the question.

+4
source

Source: https://habr.com/ru/post/1201447/


All Articles