0

I'm trying to write a general function in MATLAB that takes a function handle as one argument and a path as a second, with optional filters defining which files in the specified folder should be used. The idea is that the inputted function is then applied to all the matching files. However, I want to make sure that there's no uncontrolled crashing of this function, so I'd like to be able to check if the inputted function even takes files as input arguments.

So to sum up, I'd like to know if there's a way to find out if certain input is compatible with a certain function, with only the function handle to go on. I know MATLAB is very loose in these things but if there is a way, please do share it with me.

EDIT: I'm aware that there might be similar functions already built-in to MATLAB, I'm just looking to increase my knowledge and skill in MATLAB-coding.

Wouter
  • 161
  • 1
  • 6

2 Answers2

1

I don't think you can check if a function treats an input as a filehandle. I agree on the try/catch approach:

function foo(input_func, path)
% for testing
if nargin==0
    input_func = @(s) fprintf('Filename: %s\n', s.name);
    path = pwd;
end
% check function handle
assert(isa(input_func, 'function_handle'), 'input_func is not a valid function handle!')

% get folder contents
listing = dir(path);

for i_item = 1:length(listing)
    item = listing(i_item);
    if ~item.isdir
        try
            input_func(item)
        catch E
            warning('Function threw error for %s', item.name)
        end
    end
end

If you try replacing the 'fprintf' with eg. sin(), you should get a bunch of warnings and no nasty crashes.

  • Thanks, this is probably the best way to go. Sorry for the late acceptance, I've been busy with other things and forgot all about this... – Wouter Dec 07 '12 at 18:40
0

Something you might want to look into is try/catch:

http://www.mathworks.com/help/matlab/ref/try.html

This way you could try evaluating your function with your file(s), and if it doesn't like it, catch should capture the errors and perhaps execute a corresponding error message

Nikhil
  • 16,194
  • 20
  • 64
  • 81
Sam
  • 366
  • 1
  • 5