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?

2 views (last 30 days)
Guido on 23 Feb 2016
Commented: Guillaume on 29 Jul 2016
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.
My first attempt to import these datas to Matlab is shown below.
fid = fopen('Data.dat');
Data = textscan(fid,'%q%q', 'delimiter',';');
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

Answers (1)

Shameer Parmar
Shameer Parmar on 29 Jul 2016
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},';'],'');
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(2,:) and so on...
  1 Comment
Guillaume on 29 Jul 2016
I'm not sure why this thread has been revived. Hopefully, after 5 months the OP is still not waiting for a reply.
textscan has been part of base matlab since before R2006a. Not being able to use textscan has nothing to do with license.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!