Detect if some output arguments are not used

Matlab is entered for a character ~in the output argument list of some routine to indicate that we are not interested in this output value. For instance:

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

For reasons of speed optimization, is it possible to discover from within some procedure 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

     ...
%]
+4
source share
2 answers

It may not be the best, but a simple 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

     ...
%]
+2
source

nargout, . , , , , .

     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

    %]
0

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


All Articles