Convert dat file into fprintf using strtok, strrep and char functions
1 次查看(过去 30 天)
显示 更早的评论
I've used textscan to laod a dat file into matlab the file contains 100 lines and each line is in this format "string-001-1983-string" and i have to do the following: 1. Separate them into 3 columns so that "string-001" are in one, "1938" is in another and "string" is in the third (using strtok) 2. Then i need to remove the dash in the first column so that is read "string 001" (using strrep) 3. Finally i need to use fprintf to print them in a file with three columns and a header on each.
I have managed to use strtok to split it into 4 columns (separated at the dashes) but it's proving difficult to put the first two together again. If i do the following:
fileid = fopen('nem_skjal.dat');
if fileid == -1
disp('Error, file did not open');
else
disp('File opened successfully');
students = textscan(fileid,'%s');
% attempted to split at second dash but did not work
% [studid rest] = strtok(students,'-19')
[stud rest] = strtok(students,'-'); %stud = student
[id rest] = strtok(rest,'-'); % id = student number
[year rest] = strtok(rest,'-'); % year = birthyear
[sub rest] = strtok(rest,'-'); % sub = subject
stud_dash = strrep(stud,'i','i-')
charid=char(id{:});
charstud = char(stud_dash{:});
studid = strcat(charstud,charid);
% Failed attempts...
%stud_dash = strrep(stud,'i','i-')
%chars=char(studid{:});
%studid = [stud id];
%studid_dash = strrep(studid,'i','i-')
end
As you can see i have tried many different approaches but i get the error "Cell elements must be character arrays". That's my main error, but i get a whole bunch of others. Can anyone help me in finding the best way to do this?
Thanks in advance, Freyja
0 个评论
回答(1 个)
dpb
2013-11-3
This is a job for regexp()...
or just fix the input to fprintf()...
>> c={'string-001-1983-string'};
>> d=textscan(c{:},'%s%d%d%s','delimiter','-');
>> fprintf('%s %d,%d,%s\n',char(d{1}),d{2},d{3},char(d{4}))
string 1,1983,string
>>
2 个评论
dpb
2013-11-4
What does "didn't work" mean, specifically?
Give a sample of the input data and a desired output...
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!