convert my data from character array to numeric array

134 Views Asked by At

I am reading a plt file but I find a problem to convert my data from character array to numeric array. I tried with str2num and str2double the reulst is always : [] or NaN.

[filename pathname] = uigetfile({'*.plt'},'File Selector');
fullpathname = strcat(pathname,filename);
set(handles.text2,'string',fullpathname);%show full path name
loaddata = fullfile(pathname,filename);
fid = fopen(loaddata, 'r');% Read the entire file into memory
contents = fread(fid,'*char')';
fclose(fid);
contents = strrep(contents, ',', '.')% Replace `,` with `.`
data = str2double(contents)% Now convert to numbers`

U find here some sample from contents:

+8.7595000000000000E+03      +0.0000000000000000E+00    
+0.0000000000000000E+00      +8.3581639938152974E-01   
+0.0000000000000000E+00      +4.6014153848539308E+01  
+4.6014153852568526E+01      +0.0000000000000000E+00  
+0.0000000000000000E+00      +8.3581639938152974E-01  
+0.0000000000000000E+00      +2.2902134241670819E+01` 
1

There are 1 best solutions below

2
On

In order to convert a string that contains multiple numbers separated by whitespace, you'll want to use str2num and not str2double.

str2double expects a single number as a string or a cell array of strings and if you feed it anything else, will return a NaN.