Danny_Kim
Danny_Kim

Reputation: 299

How can I use a function as another function's parameter?

I am tried to make two m-files. one is insertion sort and the other is for checking running time.

My first m-file is '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

My second m-file is '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

I tried to type the following in the command window.

check_running_time(Insertion_sort);

As you know, I hope the result like the following

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

I am using MATLAB R2013a version. Please help me TT... Matlab is as good as C, but it is unaccustomed for me yet.

Upvotes: 2

Views: 59

Answers (2)

Jørgen
Jørgen

Reputation: 863

Instead of using feval you could use function handles see 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

And calling it with

check_running_time(@Insertion_sort)

notice the @, it is used to make a function handle. It is effectively the same, but I think the syntax is nicer.

Upvotes: 2

scmg
scmg

Reputation: 1894

You can use 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

In this case, you have to call it in Command Window as:

check_running_time('Insertion_sort')

Upvotes: 0

Related Questions