How can I import a text file which includes a mix of string and numbers without losing the information if a variable is a strings or a number?
3 views (last 30 days)
Show older comments
Hello,
I have to import text files which include a mix of strings and numbers. Each line of a textfile contains the name and the related value of a variable. Names and values are delimited by semicolons. Unfortunately the string variables can also obtain a semicolon.
String001;"ABCDEF"
String002;"ABC;DEF"
Number001;42
String003;"ABCD"
Number002;84
My first attempt to import these datas to Matlab is shown below.
fid = fopen('Data.dat');
Data = textscan(fid,'%q%q', 'delimiter',';');
fclose(fid);
So far everything works well. I get a 1x2 cell array with the names of the variables in the first cell and the values of the variables in the second cell. My problem is that the double quotation marks in the values of the string variables vanish due to the import. So I can't see anymore if the variable was initially a strings or a numbers. Is there any easy way to get these information back? Maybe with a second textscan?
Best Regards Guido
1 Comment
George
on 28 Jul 2016
Are you ever going to have numerical strings? e.g., "55" vs. 55 after the semicolon.
Answers (1)
Shameer Parmar
on 29 Jul 2016
@Guido:
For me the command textScan is not working, I guess because of some license issue.. So I trying another method as follows:
Data = textread('FileName.txt', '%s', 'delimiter', '');
NewData = {};
for i=1:length(Data)
newData{i,1} = strtok(Data{i},';');
newData{i,2} = strrep(Data{i},[newData{i,1},';'],'');
end
This will create new variable called 'newData' with n number of rows and 2 columns..
to see the output, just type "newData"
newData =
'String001' '"ABCDEF"'
'String002' '"ABC;DEF"'
'Number001' '42'
'String003' '"ABCD"'
'Number002' '84'
The first column will be the variable name and the second column will be the value..
You can also see, by typing,
newData(1,:)
newData(2,:) and so on...
1 Comment
See Also
Categories
Find more on Text Files 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!