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 次查看(过去 30 天)
显示 更早的评论
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 个评论
George
2016-7-28
Are you ever going to have numerical strings? e.g., "55" vs. 55 after the semicolon.
回答(1 个)
Shameer Parmar
2016-7-29
@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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!