Equivalent to a comma operator in MATLAB?

JavaScript and C and some other languages ​​have a comma operator that allows you to write things like (e1, e2)where e1and e2are expressions and evaluate e1, discard the result, then evaluate e2. This is often useful when converting source code.

Is there a way to do something like this in MATLAB? For example, if I have this code:

a = f() + g()

I would like to do this somehow:

a = (disp('about to call f'), f()) + (disp('about to call g'), g())

It will print about to call f, then call f, then print about to call g, then call g. But I do not want to change the structure of the code or introduce new instructions. Is it possible?

+4
source share
1 answer

I think you could just write a function:

function varargout = display_then_run(fun, varargin)
    fprintf('about to call %s\n', func2str(fun));
    [varargout{1:nargout}] = fun(varargin{:});
end

and now

a = display_then_run(@f) + display_then_run(@g)
+2
source

Source: https://habr.com/ru/post/1529365/


All Articles