Why does assigning a string object into a double vector of doubles give NaN instead of an error?

18 views (last 30 days)
I noticed that assing a string object to a double array, for example,
a=0
a(1)="asd"
does not produces an error but sets the value of a(1) to NaN;
This seems inconsistent with assinging an incompatible type like for example a cell array, e.g.
a=0
a(1)={'asd'}
---> Conversion to double from cell is not possible.
I would prefer a string assignment to double to also raise an error. Any ideas about why it does not?

Accepted Answer

Steven Lord
Steven Lord on 7 Jul 2020
Edited: Steven Lord on 7 Jul 2020
MATLAB knows how to convert double arrays to string arrays and vice versa. For the former see this documentation page, for the latter see the "Create, Concatenate, and Convert" section on this documentation page. But if the string is not a text representation of a number, the double value of the string is NaN.
>> d1 = 0:5;
>> s1 = string(d1)
s1 =
1×6 string array
"0" "1" "2" "3" "4" "5"
>> d2 = double(s1)
d2 =
0 1 2 3 4 5
>> d3 = double("abracadabra")
d3 =
NaN
MATLAB does not know how to convert a cell array to double.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!