Array indexing can be used for efficient array preallocation. For instance
2(ones(1, 3))
ans =
2 2 2
but this does not work with NaN or Inf
NaN(ones(1, 3))
ans = NaN
Why ?
Array indexing can be used for efficient array preallocation. For instance
2(ones(1, 3))
ans =
2 2 2
but this does not work with NaN or Inf
NaN(ones(1, 3))
ans = NaN
Why ?
NaN
andInf
look like special variables, when used without parenthesis.But they are actually functions.
NaN(ones (1, 3))
expands toNaN ([1, 1, 1])
which apparently is evaluated likeNaN (1, 1, 1)
. That is to a1x1x1
array, which has only a single element.The correct way to initialize a 1x3 NaN array is
Same for
Inf
.Following @carandraug suggestion, here is a slight digression.
One might also use
NaN ()(ones(1, 3))
.In this expression,
NaN ()
evaluates to theNaN
scalar value (not a function anymore).ones(1, 3)
evaluates to[1, 1, 1]
.So an intermediate step could be read as
<NaN scalar value>([1 1 1])
.Then remember how indexing works. Indexing of an array
A
with an array of integersindexes
is writtenA(indexes)
. For instanceThis prepares an array of the same size as
indexes
(1x3 here). Each element of this new array will get the value of the element ofA
having the index given by the corresponding element ofindexes
. That isSo the result of
2(ones (1, 3))
, i.e.2([1, 1, 1])
is obviously[2(1), 2(1), 2(1)]
. i.e.[2, 2, 2]
. (Remembering that a scalar can be interpreted as a single element array. So2(1)
means first element of the array[2]
, which is2
).Similarly, the intermediate step
<NaN scalar value>([1 1 1])
is finally transformed inor simply
[NaN, NaN, NaN]
.