2015-09-17 37 views
2

我試圖製作兩個m文件。 一個是插入排序,另一個用於檢查運行時間。如何將函數用作另一個函數的參數?

我的第一個m文件是'Insertion_sort.m'。

function result = Insertion_sort(raw) 

temp = raw; % temporary variable for preserving input(raw) data. 
tic; % tic Start a stopwatch timer 

% repeat n-1 times, where n is the number of input data's elements. 
for j = 2 : length(temp) 
    key = temp(j); % set pivot from 2nd to n-th element. 
    i = j - 1; % set i for comparison with pivot. 

    % repeat at most j-1 times. 
    % when key is greater than or equal to i-th element, repetition stops. 
    while i>0 && temp(i) > key 
     temp(i+1) = temp(i); % shift element to the right side. 
     i=i-1; % prepare to compare next one with pivot. 
    end 
    temp(i+1) = key; % after finishing shifting, insert pivot. 
% fprintf('[Turn %d] Pivot value: %d\n', j-1, key); 
% fprintf('#(inner loop): %d\n', j-i-1); 
% fprintf('%3d ', temp); 
% fprintf('\n\n'); 
end 

result = toc; % toc Read the stopwatch timer. 
end 

我的第二個m文件是'check_running_time.m'。

function result = check_running_time(func) 

for i = 0 : 1000 : 500000 
    data = floor(rand(1, i) * 10000); 
    elapsed = Insertion_sort(data) 
    fprintf('%6d: %3.4f\n', i, elapsed); 
end 

end 

我試圖在命令窗口中鍵入以下內容。

check_running_time(Insertion_sort); 

如你所知,我希望像下面

0: 0.0001 
1000: 0.0002 
2000: 0.0003 
... 
100000: 1.0000 

我使用MATLAB R2013a版本的結果。 請幫我TT ... Matlab和C一樣好,但它對我來說還不習慣。

回答

0

您可以使用feval

function result = check_running_time(func) 
for i = 0 : 1000 : 500000 
    data = floor(rand(1, i) * 10000); 
    elapsed = feval(func, data) 
    fprintf('%6d: %3.4f\n', i, elapsed); 
end 
end 

在這種情況下,你必須把它調用命令窗口爲:

check_running_time('Insertion_sort') 
2

而不是使用feval你可以使用功能的處理看Function Handles

function result = check_running_time(func) 
for i = 0 : 1000 : 500000 
    data = floor(rand(1, i) * 10000); 
    elapsed = func(data); 
    fprintf('%6d: %3.4f\n', i, elapsed); 
end 

然後用

check_running_time(@Insertion_sort) 

注意@,它用來做一個函數句柄。它實際上是相同的,但我認爲語法更好。

相關問題