xlsread loop through cell array

조회 수: 1 (최근 30일)
Benjamin Cowen
Benjamin Cowen 2017년 7월 19일
댓글: Geoff Hayes 2017년 7월 20일
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개)

Geoff Hayes
Geoff Hayes 2017년 7월 19일
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
Benjamin Cowen
Benjamin Cowen 2017년 7월 19일
Does this treat Ymean has a column for each file? Because Ymean is not a single value, it is a column of values
Geoff Hayes
Geoff Hayes 2017년 7월 20일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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