PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How to determine if an output of a function-call is unused?

 August 18, 2022     matlab, output     No comments   

Issue

Say I have a function foo that can return three values given an input:

function [a,b,c] = foo(input)

The calculations of variables b and c take a long time, so sometimes I may wish to ignore their calculation within foo. If I want to ignore both calculations, I simply call the function like this:

output1 = foo(input);

and then include nargout within foo:

if nargout == 1
    % Code to calculate "a" only
else
    % Code to calculate other variables

The problem occurs if I want to calculate the last output, but not the second. In that case my function call would be:

[output1,~,output3] = foo(input);

Now if I use nargout within foo to check how many outputs are in the function-call, it will always return 3 because the tilde operator (~) is considered a valid output. Therefore, I cannot use nargout to determine whether or not to calculate the second output, b, within foo.

Is there any other way to do this? I.e., is it possible to check which outputs of a function-call are discarded from within the function itself?


Solution

The commenters are basically right; this is not something that can be totally solved by the user unless The MathWorks adds functionality. However, I wrote a small function, istilde (Wayback Machine Archive), a while back that attempts to do what you ask. It works in many cases, but it's really a bit of hack and not a totally robust solution. For example, I did not attempt to get it to work for functions called from the Command Window directly (this could potentially be added with some work). Also, it relies on parsing the actual M-file, which can have issues. See the included demo file for how one might use istilde.

Feel free to edit my code for your needs – just don't use this in any production code due to the robustness issues. Any improvements would be welcome.



Answered By - horchler
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing