MATLAB: How to load numeric & string data from .txt file

load multiple type text data numeric stringsMATLAB

Dear all,
It might be a regular and common topic but I am unable to fix this issue properly.
Starting from a .txt file (let's say data.txt):
data_name1 data_name2 data_name3
0 OK 0,1,2
1 NOK 0,2.05E-05,8.5
Goal is to have in matlab workspace:
data_name1 = [ 0 ; 1 ]
data_name2 = {'OK','NOK'}
data_name3 = [ 0 1 2 ; 0 2.05E-05 8.5]
I tried readtext.m from file exchange but take huge amount of time and need lots of specific treatment afterward. Using eval also increased processing time of my function. Note: I have no specific toolbox apart from simulink.
Thanks in advance,
Pierre

Best Answer

This should do it, for your specific case:
fid = fopen('data.txt', 'rt');
C = textscan(fid, '%d %s %f,%f,%f', 'HeaderLines', 1, 'CollectOutput', true);
fclose(fid);
data_name1 = C{1};
data_name2 = C{2};
data_name3 = C{3};