adding a string to an empty array gives `NAN`

Viewed 184

In MATLAB, I would like to iteratively add string to array s, and I initialized s by s = []. However, when I run the code below

s = [];
s(end+1) = "a";
s(end+1) = "b";

it results in

>> s

s =

   NaN   NaN

Does anyone know the reason behind and any workaround for this issue?


However, when I have already "" in s, i.e., s = [""], then all the following elements can added to s without problem:

s = [""];
s(end+1) = "a";
s(end+1) = "b";

gives

s = 

  1×3 string array

    ""    "a"    "b"
2 Answers

When you initialize a new array:

s = []

s is, by default, of class double.

So when you try to add a new string in this array, matlab try to do an implicit casting string -> double. And matlab output a NaN when it has to deal with a string -> double conversion (except if this string can be interpreted as a number as mentionned by @CrisLuengo). For example:

double("a") 
% Produce Nan

Instead of initializing your array with [], you can explicitly choose the datatype of your array with strings:

s = strings(0); % We create a 0x0 strings array. 
s(end+1) = "a";
s(end+1) = "b";

And we get:

s = 

  1×2 string array

    "a"    "b"

When you initialize an array already containing an empty string, matlab understand that it needs to produce a strings array.

To add to obchardon’s correct answer (read that first!):

  1. Converting a string to double produces NaN when the string cannot be interpreted as a number. double("1") returns 1.

  2. There is a difference between string and char array. OP’s code would work fine after replacing " with ', as characters can always be converted to double (resulting in their ASCII value). But then it only works with single characters, multiple characters (an array of characters) would cast to an array of doubles, one per character, and that wouldn’t fit into a single array element.

    >> s = [];
    >> s(end+1) = 'a';
    >> s(end+1) = 'b';
    >> s
    s =
        97    98
    
Related