MATLAB: How to loop this code for several data files and finally accumulate all the plots together

loops

I have a code:
B=load('Data1.dat');
Dat=[B(:,1) B(:,2)];
nbins=[1000 1000];
n=hist3(Dat,nbins);
n1 = n;
n1(size(n,1) + 1, size(n,2) + 1) = 0;
xb1 = linspace(min(Dat(:,1)),max(Dat(:,1)),size(n,1)+1);
yb1 = linspace(min(Dat(:,2)),max(Dat(:,2)),size(n,1)+1);
figure
pcolor(xb1,yb1,n1);
xaxis= 0:0.1:40;
set(gca, 'Xticklabel', {xaxis})
set(gca, 'Yticklabel', {xaxis})
xx1=sum(n1);
I want to reapeat this code for Data1.dat, Data2.dat, Data3.dat,…….Datan.dat and finally put the results in a single plot like:
plot(xb1, xx1,':b',xb2,xx2,':r',......xbn,xxn,':k')
where xb2,xb3…xbn and xx2,xx3….xxn are the values of xb1 and xx1 in the code for second third etc… nth run(corresponding to each Data fle).

Best Answer

There are several solid ways to do this. Here is a guide for some of the components of what you want to do.
Start your code with the commands
figure
hold on
which will set up one figure for all your lines.
Wrap your data loading and drawing commands (except for the figure command) in a loop
for nf = 1:7
% Your code
end
For loading different files inside the loop, do something like this:
B{nf} = load(['Data',num2str(nf),'.dat']);
[The sprintf command is also good to construct the file name.]
Refer to B{nf} rather than B later in the code.
The final figure will have lines that are all the same color (I think). Post another question or comment if you get this far and can't figure out how to fix that. Hint: This will help: http://www.mathworks.com/help/matlab/ref/set.html