From: James Tursa on
Walter Roberson <roberson(a)hushmail.com> wrote in message <hmkr1n$neu$1(a)canopus.cc.umanitoba.ca>...
> Doug Schwarz wrote:
> > In article <hmkkoo$phj$1(a)fred.mathworks.com>,
> > "Adam Hartshorne" <adam.hartshorne(a)gmail.com> wrote:
> >
> >> Say I have a function X, that takes an input Y and returns an array / matrix.
> >> Now I really only want the nth element of the array / matrix.
> >>
> >> Obviously I could do,
> >>
> >> temp = X(Y)
> >> wantedVar = temp(n) ;
> >>
> >> Is there an easy way of doing both operations in a single line of code,
>
> > It's a FAQ and the answer is no.
>
> Depends what you mean by 'easy' and what you mean by "single line".
>
> nth = @(v,n) v(n); %define this once
>
> then
>
> wantedVar = nth(X(Y),n);
>
>
> If this is not acceptable because it uses an utility function, then
>
> wantedVar = subsref(X(Y), struct('type','()','subs',n));
>
>
> Note: both of these methods have the shortcoming of not handling 'end'.

But neither of these methods actually buys you anything. You still have to get the matrix result first and then index into it to get the nth element. That's the only way to do it in MATLAB unless the function itself supports returning only the nth element with some special syntax. Here is another one liner that (obviously) buys you nothing over the original two liner :)

temp = X(Y); wantedVar = temp(n) ;

Bottom line for OP: Stick with your two line syntax. It is fundamentally the only way to do it in MATLAB and it is easy to read and understand what is going on.

James Tursa