我编写了以下函数,将.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
是一个字符串吗?
答案 0 :(得分:4)
您必须将该函数保存在名为calc_avg.m
的单独文件中(在MATLAB路径中的当前文件夹或文件夹中),并从单独的脚本或命令行运行它
pathName = 'path/to/file';
[Daily, Hourly] = calc_avg(pathName)
您可能会收到错误,因为您尝试使用Run(f5)在编辑器中将该函数作为脚本运行。