【发布时间】:2012-02-16 16:58:38
【问题描述】:
我编写了以下将 .txt 文件导入MATLAB 的函数。 .txt 文件可以按小时或 4 分钟间隔记录,根据初始分辨率,脚本将计算每小时或每天的平均值。
function [Daily, Hourly] = calc_avg(pathName)
TopFolder = pathName;
dirListing = dir(fullfile(TopFolder,'*.txt'));%#Lists the folders in the directory
%#specified by pathName.
for i = 1:length(dirListing);
fileToRead1{i} = (dirListing(i).name);
%#lists all of the .txt files in the TopFolder
end
cell_all = arrayfun(@(i1)importdata(fullfile(pathName,dirListing(i1).name)),...
(1:length(dirListing))','un',0); %#'
%# Apply function to each element of the array.
d = cat(2,cell_all{:});
%# Concatenate arrays along each column (i.e. 2).
%# Find the length of the dataset, which will provide information on the
%# amount of averaging required.
if length(d) == 365,...
error('error: daily averages already calculated'); %#'
elseif length(d) == 8760;
daily = squeeze(mean(reshape(d,24,size(d,1)/24,[])));
elseif length(d) == 131400;
hourly = squeeze(mean(reshape(d,15,size(d,1)/15,[])));
daily = squeeze(mean(reshape(d,360,size(d,1)/360,[])));
end
%# Find which averages have been calculated:
A = exist('hourly','var');
%# If A == 1 means that hourly values had to be calculated therefore
%# the data if of high resolution (minutes).
if A == 1;
hourly = mat2cell(hourly,size(hourly,1),cellfun('size',cell_all,2)).'; %#'
daily = mat2cell(daily,size(daily,1),cellfun('size',cell_all,2)).'; %#'
elseif A == 0;
daily = mat2cell(daily,size(daily,1),cellfun('size',cell_all,2)).';%#'
end
%# Create cell in the same format as 'cell_all' where cellfun applies the
%# same function to each cell in a cell array. 'size' is used to create
%# the same format.
for i=1:length(dirListing);
[~,name{i}] = fileparts(fileToRead1{i});
%# Obtain the name of each of the .txt files (dirListing)
end
%#Generate a structure for the averages calculated.
if A == 1;
for i=1:length(dirListing);
Daily.(genvarname(name{i})) = daily{i};
Hourly.(genvarname(name{i})) = hourly{i};
end
elseif A == 0;
for i=1:length(dirListing);
Daily.(genvarname(name{i})) = daily{i};
end
end
如果我只是将它作为脚本运行,即避免使用该函数,只需在第二行中输入路径名称,该脚本就可以正常工作。但是,一旦我尝试使用 if 作为函数,它就无法工作。它会产生错误:
Error in calc_avg (line 15)
TopFolder = pathName;
我做错了什么?会不会因为pathName是字符串而出现问题?
【问题讨论】:
-
我假设您在 calc_avg.m 的前 13 行中只有 cmets?
-
没有错误说明?
-
是的,第一行是 cmets。出现错误是因为如果 A == 0,则 Hourly 将不存在,因此 matlab 显示错误。我所要做的就是添加 Hourly = [];在最后的循环中。我现在需要做的就是找到一种方法将生成的变量保存到同一目录中。感谢您的帮助。