MATLAB Answers

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?

1 ビュー (過去 30 日間)
Guido 2016 年 2 月 23 日
コメント済み: Guillaume 2016 年 7 月 29 日
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
  1 件のコメント
George 2016 年 7 月 28 日
Are you ever going to have numerical strings? e.g., "55" vs. 55 after the semicolon.


回答 (1 件)

Shameer Parmar
Shameer Parmar 2016 年 7 月 29 日
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 件のコメント
Guillaume 2016 年 7 月 29 日
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.


Community Treasure Hunt

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

Start Hunting!

Translated by