How Read text file as array form , Please
1 view (last 30 days)
Show older comments
Hi ,
i have text file (data) , i need store each word or number as array (x,y):as in attach file
for example:
line 1: 413733000: system.cpu15.icache: ReadReq [10574:10577] IF hit state: 5 (S) valid: 1 writable: 0 readable: 1 dirty: 0 tag: 8
line2: 413733000: system.cpu00.icache: ReadReq [6e4ef8:6e4efb] IF hit state: 5 (S) valid: 1 writable: 0 readable: 1 dirty: 0 tag: 372
store in array as :
c(1,1)=413733000 c(1,2)= system c(1,3)=cpu15 c(1,3)= icache ...etc. to the line 1
c(2,1) =413733000 c(2,1)=system c(2,2)=cpu00 c(2,3)=ichahe ..etc.. to the line 2
i appricate for any help
4 Comments
Rik
on 21 Aug 2019
You misunderstood: I meant what code did you already try.
Also, it might be a better idea to parse each line, instead of chopping it up into smaller pieces. And you probably want a struct array.
Answers (1)
Rik
on 21 Aug 2019
The code below should get you most of the way there. The idea is to parse each element and then remove it from the variable, so every part is independent and can in principle be replaced by some parsing function you would write. This code does rely on you having read the file to a cell array, but that shouldn't really be a problem. You can even use my readfile FEX function if you're in a hurry.
c={'413733000: system.cpu15.icache: ReadReq [10574:10577] IF hit state: 5 (S) valid: 1 writable: 0 readable: 1 dirty: 0 tag: 8',...
'413733000: system.cpu00.icache: ReadReq [6e4ef8:6e4efb] IF hit state: 5 (S) valid: 1 writable: 0 readable: 1 dirty: 0 tag: 372'};
out=struct;
for n=1:numel(c)
str=c{n};
idx=strfind(str,':');
ID=str(1:(idx(1)-1));
str(1:(idx(1)+1))='';%chop off ID
idx=strfind(str,':');
CPU=str(1:(idx(1)-1));
str(1:(idx(1)+1))='';%chop off CPU
idx1=strfind(str,'[');idx1=idx1(1)+1;
idx2=strfind(str,']');idx2(idx2<idx1)=[];idx2=idx2(1)-1;
MemoryAddress=str(idx1:idx2);
str(1:(idx2+2))='';%chop off MemoryAddress
%etc
%store to output struct
out(n).ID=ID;
out(n).CPU=CPU;
out(n).MemoryAddress=MemoryAddress;
%etc
end
4 Comments
Rik
on 21 Aug 2019
Have you read the documentation for fopen? It generates a handle to a file, it isn't the file contents. If you have an error or unexpected output when using a function, read the documentation first.
Either use fgetl (and replace the for-loop by a while loop, don't forget setting n to 0 and incrementing it inside the loop) or use my readfile function. Note that it is often much faster to load the entire file that to read line by line.
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!