我试图制作两个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/