MATLAB: For loop involving concatenation

concatenatestrings

Hi,
I have a set of data in Excel and want to get the data out and plot. I have been trying to create a for loop unsuccessfully. I want to loop from the letter D-H and then let it loop through. Currently I repeat the commands one by one as below:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%A: Decay of Centreline Peak Velocity
xl = xlsread('lateraldispersion.csv','C3:C9');
Dexp = xlsread('lateraldispersion.csv','D3:D9');
Eexp = xlsread('lateraldispersion.csv','E3:E9');
Fexp = xlsread('lateraldispersion.csv','F3:F9');
Gexp = xlsread('lateraldispersion.csv','G3:G9');
Hexp = xlsread('lateraldispersion.csv','H3:H9');
hold on
plot (xl, Dexp,'ok','linewidth',2.5);
plot (xl, Eexp,'--b','linewidth',2.5);
plot (xl, Fexp,'--r','linewidth',2.5);
plot (xl, Gexp,'--g','linewidth',2.5);
plot (xl, Hexp,'--k','linewidth',2.5);
%%%%%%%%%%%%%%%%%%%%%
Any advice on a more elegant method? Thanks!

Best Answer

Hi Kyze, here's method 1, which is just to replace your repeated code with a loop (one to read from excel, one to plot):
columnSet = 'CDEFGH';
colourSet = {'ok','--b','--r','--g','--k'};
xl = xlsread('lateraldispersion.csv','C3:C9');
expSet = cell(size(columnSet));
for i = 1:length(expSet)
expSet{i} = xlsread('lateraldispersion.csv',[columnSet(i) '3:' columnSet(i) '9']);
end
figure, hold on
for i = 1:length(expSet)
plot (xl, expSet{i},colourSet{i},'linewidth',2.5);
end
Here's method 2, which is to avoid the loop altogether and just load all your data as one matrix.
allData = xlsread('lateraldispersion.csv','C3:H9');
colourSet = {'ok','--b','--r','--g','--k'};
figure, hold on
for i = 1:length(expSet)
plot (allData(:,1), allData(:,i+1),colourSet{i},'linewidth',2.5);
end
I think method 2 is much better, as it avoids the multiple calls to xlsread.
Method 3 even reduces things to just 2 simple lines of code, as long as you're happy with the default MATLAB colour sets.
allData = xlsread('lateraldispersion.csv','C3:H9');
figure, plot(allData(:,1), allData(:,2:end), 'linewidth',2.5)