Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Controlling outputs when creating anonymous functions

Subject: Controlling outputs when creating anonymous functions

From: Sky Sartorius

Date: 21 Jan, 2013 12:33:07

Message: 1 of 1

I want to create an anonymous function with more control over the outputs.

For a generic example, working with [T, A, P, RHO] = atmosisa(H), I want an anonymous function that gives me air density, rho, as a function of altitude, for example so I can pass it to fzero to find density altitude. However, fzero only cares about the first output, T, and I only care about the fourth output, rho.

The only way I can think to do this in a script was to make another function:

function varargout = outputselect(ind,fx,varargin) %#ok<INUSD>

nout = max(ind);

alphabet = '[a b c d e f g h i j k l m n o p q r s t u v w x y z';
str = [alphabet(1:(2*nout)) ']'];
eval([str ' = fx(varargin{:});']);

varargout = cell(1,nout);
for ii = 1:length(ind)
    varargout{ii} = eval(alphabet(2*ind(ii)));
end
end


now I have complete control over output order and can create my anonymous function with any number/order of outputs:
atmosisa_reversed_outputs = @(h) outputselect([4 3 2 1],@atmosisa,h)


This seems not at all elegant or scalable, not to mention that it's yet another utility function that I have to have on my path. I feel like there has to be a better by using some sort of indexing I don't know about so I can communicate my intent right there in the anonymous function creation, e.g. f = @(h) atmosisa(h)[4].

And please no responses saying "if you're already making a new function/mfile..."

I'm aware of simply making a new subfunction or mfile:
function rho = atmosisa_rho(h)
[~,~,~,rho] = atmosisa(h);
end

but my actual application doesn't support that.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us