plotting multiple plots in a for loop
Mostra commenti meno recenti
I have 34 .txt files with 2 columns (x and y) of data in each, but the length of the columns in each file is variable. (as in one file may be 37x2 and another may be 75x2)
I want to load all the files and then plot them all on the same graph in a for loop. I am able to load the data successfully in the following for loop
for i = 1:34
filename = ['file',int2str(i),'.txt'];
load(filename,'-ascii');
end
I tried saving the columns in x and y arrays but I don't think it works because the columns are of different length, the code below is what I added into the for loop
MTF_filename = ['file',int2str(i)];
x(i) = MTF_filename(:,1)
y(i) = MTF_filename(:,2)
the code works but it takes the 1st and 2nd column 1 to 34 times of the string MTF_filename instead of using the array associated with the name file1, file2, file3 etc. so I end up with x = MMMMMMM.... and y = TTTTTTT.... I'm not sure how to fix this and afterwards i'm not sure how to proceed with the plotting.
Risposta accettata
Più risposte (2)
Joseph Cheng
il 2 Set 2014
in your
MTF_filename = ['file',int2str(i)];
x(i) = MTF_filename(:,1)
y(i) = MTF_filename(:,2)
you're trying to save a Mx1 into a 1x1 index. you should consider using cells as you can store them with varying lengths.
example:
figure,hold on
linecolor = hsv(10);
for i=1:10
l = randi(10,1,1);
x{i}=randi(10,1,l);
y{i}=randi(10,1,l);
plot(x{i},y{i},'color',linecolor(i,:))
end
Something like this should work if all you want to do is plot the data and not keep all the data for subsequent processing. Then you needn't worry about structures to store different sized columns in.
figure; hold on
for i = 1:34
filename = ['file',int2str(i)];
load([filename '.txt'],'-ascii');
plot( filename(:,1), filename(:,2) );
end
That "plot( filename(:,1), filename(:,2) );" looks a bit silly, but I'm not familiar with loading ascii files and it seems that default behaviour for the syntax you had is for it to simply create a variable in the workspace with the same name as your file.
1 Commento
knifewrench
il 3 Set 2014
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!