Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Mental Model for feval

What's your mental model for when to use the MATLAB function 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;
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;
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.

  • print
  • send email


댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.