2017-07-19 61 views
0

我的代码发布在下面。它正是我需要它做的。MATLAB循环通过excel文件

它读入一个文件并绘制我需要的数据。如果我想读另一个文件并让它通过相同的代码,而不必用不同的变量再次编写整个文件,那可能吗?我想存储每个循环的矩阵。

正如你可以看到我得到的文件名为:Oxygen_1keV_300K.xlsx

我有叫另外一个文件:Oxygen_1keV_600K.xlsx

等。

如何循环浏览这些文件而不必重新编码整个事物?然后我想在同一个图上绘制它们。最好为每个文件存储最终的矩阵Y和Ymean,这样它们就不会被覆盖。

clear 
clc 


files = ['Oxygen_1keV_300K','Oxygen_1keV_300K','Oxygen_1keV_600K','Oxygen_1keV_900K']; 
celldata = cellstr(file) 

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) 
+0

我建议使用['dir'](https://www.mathworks.com/help/matlab/ref/dir.html)或['ls'](https://www.mathworks.com/帮助/ matlab/ref/ls.html)函数来获取文件列表,然后使用for循环来遍历它们。 – Cecilia

+0

我不想获取目录中的所有文件。我正在考虑创建Ymean {i}。我怎样才能给我想要循环的文件列表? – Jack

+0

您也可以手动定义文件路径字符串的单元阵列,并循环执行。 – Cecilia

回答

1

单元格数组使得存储可以作为for循环的一部分访问的字符串列表非常容易。在这种情况下,我建议把你的文件路径中的单元阵列作为用于您的呼叫xlsread

例如使用的字符串的替代品,

%The first file is the same as in your example. 
%I just made up file names for the next two. 
%Use the full file path if the file is not in your current directory 
filepath_list = {'C:\Users\Ben\Desktop\Oxygen_1keV_300K.xlsx', 'file2.xlsx', 'file3.xlsx'}; 

%To store separate results for each file, make Ymean a cell array or matrix too 
YMean = zeros(length(filepath_list), 1); 

%Now use a for loop to loop over the files 
for ii=1:length(filepath_list) 
    %Here's where your existing code would go 
    %I only include the sections which change due to the loop 
    for k=1:24 
     %The change is that on this line you use the cell array variable to load the next file path 
     data{k} = xlsread(filepath_list{ii},['PKA', num2str(k)]); 
    end 
    % ... do the rest of your processing 
    %You'll need to index into Ymean to store your result in the corresponding location 
    YMean(ii) = mean(Y, 2); 
end 

单元阵列是一个基本的matlab变量类型。对于一个简介,我建议单元阵列中的文档for creatingaccessing数据。

如果您的所有文件都在同一个目录中,您还可以使用像dirls这样的函数以编程方式填充单元阵列。

+0

我刚刚在我的例子中使用了文件名,但是如果这些文件不在你当前的目录中,只需使用完整的文件路径来使用文件名。我将编辑示例。 – Cecilia

+0

我明白了。你能否澄清我如何编辑Ymean成为循环的一部分?目前Ymean将只是最后一个循环。我如何为每个循环存储Ymean?它只是Ymean {ii} – Jack

+0

您需要将Ymean定义为单元阵列或矩阵。我刚刚添加到示例中。 – Cecilia