3

Let's say I have

function [a, b] = foo
a = 1;
b = 2;

and the user is calling

[~, B] = foo;

I would like only b = 2 to happen, to prevent a time consuming operation a = 1. Is there a way to find out that a was actually not requested by user?

Long ago it was not possible. I wonder if Mathworks improved this or anyone found a workaround in the meantime.

Note: the opposite is possible: if user calls A = foo, the nargout is 1.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
texnic
  • 3,959
  • 4
  • 42
  • 75

1 Answers1

0

It is not possible for good reason. Just because you do not require the middle output at the point of return of the function, doesn't mean that its calculation was unnecessary within the function, unless you explicitly write your function to do so.

E.g., it is possible that the calculation of output 3 depends on output 2 inside the function, even if not explicitly requested at output time). Matlab has no way of knowing this, so it cannot assume that any and all calculations involving that output can be discarded.

If you require a memory efficient manner of ensuring only the correct calculations take place, then change your output strategy.

I would suggest returning a struct with the right fields, where you request the fields you desire at function calling. In this way, your final struct would only contain the fields you desire, and you can ensure inside your function that unnecessary calculations do not take place.

Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57