xlsread loop through cell array

I have the following code. I created a cell array with filetypes. You can see in my xlsread I just have one file name. How can I replace this a loop that goes through my cell array with different names and create Ymean{i} instead of just Ymean?
close all
clear
clc
filenames = ['Oxygen_1keV_300K','Oxygen_1keV_300K','Oxygen_1keV_600K','Oxygen_1keV_900K'];
celldata = cellstr(filenames)
k = cell(1,24);
for k=1:24
data{k} = xlsread('C:\Users\Ben\Desktop\Oxygen_1keV_300K.xlsx',['PKA', num2str(k)]);
end
for i=1:24
xfinal{i}=data{1,i}(end,1);
xi{i}=0:0.001:xfinal{i};
xi{i}=transpose(xi{i});
x{i}=data{1,i}(:,1);
y{i}=data{1,i}(:,4);
yi{i} = interp1(x{i},y{i},xi{i});
end
Y = zeros(10001, numel(data));
for ii = 1 : numel(data)
Y(:, ii) = yi{ii}(1 : 10001);
end
Ymean = mean(Y, 2);
figure (1)
x=0:0.001:10;
semilogy(x,Ymean)
grid on
xlabel('Time (ps)')
ylabel('Oxygen Vacancies')

回答(1 个)

Benjamin - if all files are in the same directory, you could do
filenames = {'Oxygen_1keV_300K','Oxygen_1keV_300K','Oxygen_1keV_600K','Oxygen_1keV_900K'};
data = cell(1,length(filenames));
YMean = zeros(1, length(filenames));
for k=1:length(filenames)
sFilename = [fullfile('C:\Users\Ben\Desktop\', filenames{k}) '.xlsx']
data{k} = xlsread(sFilename,...);
% do your calculations on data{k}
% calculate and save the mean
YMean(k) = ...;
end
Note how we create a cell array of filenames by using the curly braces {} rather than concatenating the strings together using the square brackets []. We then iterate over each element in the filenames array and create a full filename, sFilename, which has a path to the file with the xlsx extension.

2 个评论

Does this treat Ymean has a column for each file? Because Ymean is not a single value, it is a column of values
Benjamin - if Ymean is a column, does it have the same dimension for each file or can it be different? If the former, then just initialize as a matrix. Else if the latter, then use a cell array.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by