2011-04-03 117 views
0

如何將此腳本轉換爲MATLAB函數?如何將此腳本轉換爲MATLAB函數?

clear all; 

set={AB02XY_1,ZT99ER_1,UI87GP_1}; 

fileData1 = load([fileString set{1} '.mat']); 
fileData2 = load([fileString set{2} '.mat']); 
fileData3 = load([fileString set{3} '.mat']); 

[A,B] = myfunction1_1(fileData1,fileData2,fileData3); 

fileName = 'C:\Users\Documents\MATLAB\matrice_AAA001.mat'; 
save(fileName,'A','B'); 

clear all; 

set={AB02XY_2,ZT99ER_2,UI87GP_2}; 

fileData1 = load([fileString set{1} '.mat']); 
fileData2 = load([fileString set{2} '.mat']); 
fileData3 = load([fileString set{3} '.mat']); 

fileData4 = load('C:\Users\Documents\MATLAB\matrice_AAA001.mat'); 

[A,B] = myfunction1_2(fileData1,fileData2,fileData3,fileData4); 

fileName = 'C:\Users\Documents\MATLAB\matrice_AAA001.mat'; 
save(fileName,'A','B'); 

我做處理大型數據文件,然後以避免錯誤「內存不足」,我每個文件分割成兩個部分,我用在每個階段的開始「清除所有」。所以,我想要的是具有AAA001 = function (AB02XY, ZT99ER, UI87GP, MyFunction1)的功能。 我的問題是我必須爲其他數據文件編寫相同的腳本。那麼,有沒有辦法構建一個函數,我可以只改變文件名AB02XY,ZT99ER,UI87GP和函數的名稱'MyFunction1'來進行子處理以獲得文件AAA001的最後一步。

注意:我簡化了腳本,但實際上我將每個文件分成5個部分。所以我想在一個函數中轉換我的腳本的5個部分!

謝謝你的幫助。

回答

1

以下是一種方法。調用函數

output = function ({'AB02XY', 'ZT99ER', 'UI87GP'}, 5, MyFunction1); 

注意,我認爲你要5個文件部分

function out = myMainFunction(fileList, nParts, fun2run) 
%# myMainFunction calculates output from multiple split files 
% 
%# SYNOPSIS out = myMainFunction(fileList, nParts, fun2run) 
%# 
%# INPUT fileList: cell array with file body names, e.g. 
%#     'AB02XY' for files like 'AB02XY_1.mat' 
%#   nParts : number of parts in which the files are split 
%#   fun2run : function handle or name. Function has to 
%#     accept lenght(fileList) arguments plus one 
%#     that is the output of the previous iteration 
%#     which is passed as a structure with fields A and B 
%# 
%# OUTPUT out : whatever the function returns 
%# 
%# Brought to you by your friends from SO 


%# input checking should go here 

if ischar(fun2run) 
    fun2run = str2func(fun2run); 
end 

nFiles = length(fileList); 


for iPart = 1:nParts 

data = cell(nFiles,1); 
for iFile=1:nFiles 

data{iFile} = load(sprintf(%s_%i.mat',fileList{iFile},iPart)); 

end 

if iPart == 1 
    %# call fun2run with nFiles inputs 
    [out.A,out.B] = fun2run(data{:}); 
else 
    %# fun2run wants the previous output as well 
    [out.A,out.B] = fun2run(data{:},out); 
end 

end %# loop parts 
0

如果我理解正確,這個函數的主要挑戰是正確彙編文件名,並傳遞應該調用的函數,對不對?如果傳遞的數據文件作爲字符串的名稱,你可以用sprintf組建一個文件名,像:

dataSetName = 'AAA001'; 
dataFilename = sprintf('C:\path\to\datafolder\%s.mat', dataSetName); 

對於函數,你可以傳遞一個function handle作爲參數傳遞給你的函數。例如,考慮一下你定義一個函數:

function c = apply_fun(fun, a, b) 
c = fun(a, b); 
end 

你可以,例如,maxmean爲FUNC,像這樣:

>> apply_fun(@max, 1, 2) 

ans = 

    2 

>> apply_fun(@min, 1, 2) 

ans = 

    1 

也就是說,到max的引用傳遞(與@max ),然後在我們定義的apply_fun函數內使用它。

此外,你不需要clear all裏面的一個函數,因爲它已經有另一個範圍。

希望這可以幫助你!