Help with data from multiple files
Ältere Kommentare anzeigen
Hi there,
First, excuse my naivety - I'm definitely no Matlab regular. And apologies if this is a repeat of an old question, but I couldn't find/understand what I'm looking for.
I have a bunch of .txt files (COTO_1_sphere.txt, COTO_2_sphere.txt, ..., COTO_26_sphere.txt) that I have managed to load in with this:
files = dir('*_sphere.txt');
for i=1:length(files)
eval(['load files(i).name ' -ascii']);
end
I now want to extract certain columns of data from the files but can not work out how to do this with a loop. At the moment I have a workaround in the form of multiple, repetitive lines of code but obviously this is not sustainable in the long term. So I'm looking for help in setting up some code that will do this quicker and save me typing excessive amounts. What I have at the moment is:
xloc1=COTO_1_sphere(:,1);
xloc2=COTO_2_sphere(:,1);
xloc3=COTO_3_sphere(:,1);
xloc4=COTO_4_sphere(:,1);
xloc5=COTO_5_sphere(:,1);
xloc6=COTO_6_sphere(:,1);
xloc7=COTO_7_sphere(:,1);
xloc8=COTO_8_sphere(:,1);
xloc9=COTO_9_sphere(:,1);
xloc10=COTO_10_sphere(:,1);
xloc11=COTO_11_sphere(:,1);
xloc12=COTO_12_sphere(:,1);
xloc13=COTO_13_sphere(:,1);
xloc14=COTO_14_sphere(:,1);
xloc15=COTO_15_sphere(:,1);
xloc16=COTO_16_sphere(:,1);
xloc17=COTO_17_sphere(:,1);
xloc18=COTO_18_sphere(:,1);
xloc19=COTO_19_sphere(:,1);
xloc20=COTO_20_sphere(:,1);
xloc21=COTO_21_sphere(:,1);
xloc22=COTO_22_sphere(:,1);
xloc23=COTO_23_sphere(:,1);
xloc24=COTO_24_sphere(:,1);
xloc25=COTO_25_sphere(:,1);
xloc26=COTO_26_sphere(:,1);
ANYHTING to improve this would be hugely appreciated. I've tried using eval and sprintf, but haven't had any luck - I'm obviously doing something wrong.
Many thanks,
James.
Akzeptierte Antwort
Weitere Antworten (1)
Geoff Hayes
am 25 Jul. 2014
James - you could try something like the following
% get the list of files that match the filter
files = dir('*_sphere.txt');
% determine the number of files
n = length(files);
% pre-allocate memory to a cell array for each column read from each file
dataArray = cell(n,1);
% iterate over each file
for k=1:n
% load the file
data = load(files(k).name,'-ascii');
% copy the first column to the array
dataArray{k} = data(:,1);
end
The above uses a cell array rather than a matrix since it is unclear whether each file has the same number of rows.
NOTE how k is used rather than i or j since both of these can be used as representation for the imaginary number.
Try the above and see what happens!
1 Kommentar
James
am 25 Jul. 2014
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!