Reputation: 2509
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 ?
Upvotes: 2
Views: 91
Reputation: 2509
NaN
and Inf
look like special variables, when used without parenthesis.
But they are actually functions.
NaN(ones (1, 3))
expands to NaN ([1, 1, 1])
which apparently is evaluated like NaN (1, 1, 1)
. That is to a 1x1x1
array, which has only a single element.
The correct way to initialize a 1x3 NaN array is
NaN (1, 3)
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 the NaN
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 integers indexes
is written A(indexes)
. For instance
A([i1, i2, i3])
This prepares an array of the same size as indexes
(1x3 here). Each element of this new array will get the value of the element of A
having the index given by the corresponding element of indexes
. That is
[A(i1), A(i2), A(i3)]
So 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. So 2(1)
means first element of the array [2]
, which is 2
).
Similarly, the intermediate step <NaN scalar value>([1 1 1])
is finally transformed in
[<NaN scalar value>, <NaN scalar value>, <NaN scalar value>]
or simply [NaN, NaN, NaN]
.
Upvotes: 3