4

Matlab introduced for the ~ character in the list of output arguments of some routine in order to indicate we're not interested in this output value. For instance:

% Only interested for max position, not max value
[~, idx] = max(rand(1, 10));

For speed optimization reasons, is it possible from inside some routine to detect that some of the output arguments are not used ? For instance:

function [y, z] = myroutine(x)
%[
     if (argout(1).NotUsed)
         % Do not compute y output it is useless
         y = []; 
     else
         % Ok take time to compute y
         y = timeConsummingComputations(x);
     end

     ...
%]

2 Answers 2

2

It may not be the best one but an easy solution is to add another input argument

function [y, z] = myroutine(x, doYouWantY)
%[
     if doYouWantY == 0
         % Do not compute y output it is useless
         y = []; 
     else
         % Ok take time to compute y
         y = timeConsummingComputations(x);
     end

     ...
%]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I think so too and that's what I have implemented so far .. will way for a while to see if there's a command under the hoods before to validate your answer.
0

nargout method, edited for 2nd output. Not very stable solution though, since whenever you call the function with one output argument, you need to be aware that the output is the second argument only.

     function [y, z] = myroutine(x)
     %[
     if nargout==1
         % Do not compute y output it is useless
         y = []; 
     else
         % Ok take time to compute y
         y = timeConsummingComputations(x);
     end

    %]

2 Comments

Here, I'm interested in being able to skip computations for the first argument, not the second (I'm not able to reorder outputs, need to preserve calling syntax)
(1) It could also work, just place the if around the first argument instead of the second. (2) Could you just input another class? So if normally it's a scalar, input a string, and check isstring, for example. (3) is adding an extra input argument that is true or false depending on whether you want to calculate that part of the code or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.