Mental Model for feval
Until Release 14 (MATLAB 7), feval was the way to evaluate a function handle. By that I mean you might write code something like this:
function y = halfcircle(fun,n) if nargin < 2 n = 20; end y = feval(fun,0:pi/n:pi);
And you would call this function like this:
ys = halfcircle(@sin); yc = halfcircle(@cos);
feval can also be used to evaluate functions when they are specified by their name.
fn = 'sin'; y = feval(fn, 0:pi/3:pi);
It is more direct however to call the function itself instead of passing it to feval:
y = sin(0:pi/3:3);
In Release 14, we removed the need to use feval to evaluate function handles. Instead, they can be evaluated directly. Here's what the halfcircle code might look like in MATLAB 7.
function y = halfcircle(fh,n) if nargin < 2 n = 20; end y = fh(0:pi/n:pi);
So, I was curious recently when I saw some code posted in the MATLAB newsgroup containing a line that looked like this:
files = feval('dir','*.gif');
This was interspersed with code containing calls to length, imread, and several other functions, all of which were called directly.
Does anyone have insight about what distinction a user might have made between the MATLAB function dir and other ones?
Please post your comments and thoughts. I'd love to hear how you think about this.
- Category:
- Function Handles,
- Readability