我的代码发布在下面。它完全符合我的需要。
它读入一个文件并绘制我需要的数据。如果我想读取另一个文件并让它通过相同的代码,而不必使用不同的变量第二次写完整个东西,那可能吗?我想存储每个循环中的矩阵。
正如您所看到的,我得到的文件名为: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 :(得分: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 creating和accessing数据。