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 ?
Copyright © 2021 Jogjafile Inc.
NaNandInflook 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 a1x1x1array, 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 theNaNscalar 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
Awith an array of integersindexesis 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 ofAhaving 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].