Matlab 如何将一个函数用作另一个函数';s参数?

Matlab 如何将一个函数用作另一个函数';s参数?,matlab,Matlab,我试图制作两个m文件。 一个是插入排序,另一个是检查运行时间 我的第一个m文件是“Insertion\u 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 inpu

我试图制作两个m文件。 一个是插入排序,另一个是检查运行时间

我的第一个m文件是“Insertion\u 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\u running\u 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
我使用的是MatlabR2013A版本。 请帮我翻译一下。。。 Matlab和C一样好,但我还不习惯它。

您可以使用:

在这种情况下,您必须在命令窗口中调用它,如下所示:

check_running_time('Insertion_sort')

您可以使用函数句柄,而不是使用
feval
,请参见

并称之为

check_running_time(@Insertion_sort)
请注意
@
,它用于生成函数句柄。实际上是一样的,但我认为语法更好

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)