Extract data from text file and save them to 3D array

9 views (last 30 days)
Hello! I have a small question here. I got some text files in form as following:
08-September-2015 10:44
28 lines in following concentration table = NCONC+1
Conc. %SD /Cr+PCr Metabolite
0.599 2% 0.106 Mac
2.216 6% 0.393 Ala
0.000 999% 0.000 Asp
......
There are some hundred lines following, too. However, I only need the first element from the fifth line (2.216), how can I extract it?
Besides, I have hundreds of this kind of files, from which I need to extract this element from above mentioned place. The files are created from a for loop with three variables. I want to save the extracted elements into a 3D array according to these three variables. Can someone help me on this?
I wrote some codes to open the files, the variables of the for loop are in the codes:
directory= 'C:\Users\karl\Documents\COORD\';
for lb=19:11:30;
for snr=20:105:230;
for GC=2.5:0.025:2.55;
filename = [directory, 'Gln', num2str(lb), 'HzSNR', num2str(snr), 'C' , num2str(GC), 'Mice'];
fid=fopen(filename);
fclose(fid);
end;
end;
end;
So, the three variables are lb, snr and GC, the files which contains the data I need are also named in a way after these three variables.
Can someone help me? Thank you very much!

Accepted Answer

Walter Roberson
Walter Roberson on 9 Sep 2015
lbvals = 19:11:30;
num_lb = length(lbvals);
snrvals = 20:105:230;
num_snr = length(snrvals);
GCvals = 2.5:0.025:2.55;
num_GC = length(GCvals)l
Your3DMatrx = zeros(num_lb, num_snr, num_GC);
for lbidx = 1 : num_lb
lb = lbvals(lbidx);
lbstr = num2str(lb);
for snridx = 1 : num_snr
snr = snrvals(snridx);
snrstr = num2str(snr);
for GCidx = 1 : num_GC
GC = GCvals(GCidx);
GCstr = num2str(GC);
filename = fullfile(directory, sprintf('Gln%sHzSNR%sC%sMice', lbstr, snrstr, GCstr));
fid = fopen(filename, 'rt');
datacell = textscan(fid, '%f', 1, 'HeaderLines', 4);
fclose(fid);
Your3DMatrx(lbidx, snridx, GCidx) = datacell{1};
end
end
end
  1 Comment
James Lorringer
James Lorringer on 9 Sep 2015
Edited: James Lorringer on 9 Sep 2015
Thank you so much @Walter Roberson! You saved my day!
Hi, could you please help me further on this program? Now I need to make a linear fit for each column of data in GC axis of the matrix. (In this 2D plot, y axis is the same as GC in the 3D matrix, on x axis are the values of the extracted data. For example,for each column, there will be three points) Thank you very much!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!