Str2double gives NaN
27 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
X = ["3.716,3.711,3.719,3.714,3.714,3.711,3.722,3.712,3.715,3.715,3.717,3.721,3.713,3.714,0.000"];
Y = str2double(X);
I am trying to convert the above string to double. However, using above code, the Y value is 'NaN'.
'str2num(X)' gives appropriate/required results.
Y = [3.71600000000000 3.71100000000000 3.71900000000000 3.71400000000000 3.71400000000000 3.71100000000000 3.72200000000000 3.71200000000000 3.71500000000000 3.71500000000000 3.71700000000000 3.72100000000000 3.71300000000000 3.71400000000000 0]
However, 'str2num' is not supported in code generation. Is there any alternative?
0 commentaires
Réponse acceptée
Stephen23
le 30 Jan 2023
X = "3.716,3.711,3.719,3.714,3.714,3.711,3.722,3.712,3.715,3.715,3.717,3.721,3.713,3.714,0.000";
str = X{1}; % character vector
idx = str==',';
idy = diff([true,idx,true]);
idb = find(idy<0);
ide = find(idy>0)-1;
num = numel(idb);
tmp = cell(num,1);
for k = 1:num
tmp{k} = str(idb(k):ide(k));
end
vec = str2double(tmp)
Plus de réponses (2)
Askic V
le 30 Jan 2023
Try this:
X = "3.716,3.711,3.719,3.714,3.714,3.711,3.722,3.712,3.715,3.715,3.717,3.721,3.713,3.714,0.000";
newStr = split(X,',')
Y = str2double(newStr)
Askic V
le 30 Jan 2023
Modifié(e) : Askic V
le 30 Jan 2023
I would also like to suggest this solution:
X = "3.716,3.711,3.719,3.714,3.714,3.711,3.722,3.712,3.715,3.715,3.717,3.721,3.713,3.714,0.200";
f = strfind(X, ","); % find indices of delimiter
Y = zeros(1, numel(f)+1); % initialize output array
X_char = convertStringsToChars(X);
j = 1;
for i = 1:numel(f)
start = j;
Y(i) = str2double(X_char(j:f(i)-1));
j = f(i)+1;
end
Y(end) = str2double(X_char(f(i)+1:end)); % add last element
Y
0 commentaires
Voir également
Catégories
En savoir plus sur Cell Arrays dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!