matlab - 如何使用一个函数作为另一个函数的参数?

标签 matlab

我试图制作两个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 一样好,但我还不习惯。

最佳答案

您可以使用函数句柄代替使用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)

注意@,它用于创建函数句柄。它实际上是相同的,但我认为语法更好。

关于matlab - 如何使用一个函数作为另一个函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621825/

相关文章:

matlab - 在 MATLAB 中绘制点时出现的问题

python - Python 和 Matlab 一起使用的最简单的数据库是什么?

c++ - 无法使用 system() 在 matlab 中运行可执行文件,但它可以在命令行中运行

python - MATLAB 无法调用带有导入的 Python 模块

matlab - Octave:脚本暂停时无法与窗口交互

matlab - 按对最短距离排序

matlab - 在 32 位或 64 位 matlab 上运行?

image - 在 MatLab 中打开正电子发射断层扫描 (PET) DICOM 图像并正确解释像素值?

matlab - 如何创建并行循环?

algorithm - 通过内置命令在matlab中计算所有N位字符串