MATLAB (MATLAB) Ignoring output arguments

  • Thread starter Thread starter juef
  • Start date Start date
  • Tags Tags
    Matlab Output
AI Thread Summary
In MATLAB, when a function returns multiple output arguments but only one is needed, users can ignore the unwanted outputs to avoid warnings and unnecessary memory usage. Instead of assigning unused outputs to dummy variables, newer MATLAB versions allow the use of the tilde (~) symbol to ignore specific outputs. For example, using [~, ~, ~, ~, ~, F] = myFun(input) effectively discards the first five outputs while retaining the sixth. This method enhances code readability and efficiency. Overall, utilizing the tilde for ignored outputs simplifies handling multiple return values in MATLAB functions.
juef
Messages
27
Reaction score
0
Hey all,

Suppose I have a MATLAB function that returns two (or more) output arguments, but I only care about the second one, and I do not wish to assign the value of the first one to a variable.

What bugs me is when, for example, I solve an ODE:

[t, x] = ode45(blablabla)

and then MATLAB editor's automatic syntax checker tells me that the variable 't' is never used. Of course it isn't, because I don't need it :P But more importantly, it uses some memory unnessarily. So, is there any way to totally ignore that argument?

Thank you all!
 
Physics news on Phys.org
I haven't used MATLAB in ages, but if a function returns a vector is it not possible to pick off one component like:

x=ode45(blablabla)[2]
 
I have been wondering exactly the same thing. Haven't found a answer, though.

Just to be clear, it is not about selecting a value of a returned vector, but selecting a specific output. It is especially annoying if I have a multiple output arguments.

function [A,B,C,D,E,F] = myFun(inputarg)
...​
end

If I only want the last output argument F I usually just do the following
[dummy, dummy, dummy, dummy, dummy, F] = myFun(input)

but its ugly.
 
edit the code or save as the original function without the extra arguments if it is really important to you.
 
Newer versions of Matlab let you use a ~ in place of the output variables you choose to ignore. So instead of

[dummy, dummy, dummy, dummy, dummy, F] = myFun(input),

you could put

[~, ~, ~, ~, ~, F] = myFun(input)

See this blog post for more info.
 
Wow, that is handy. Thanks for the link.
 
Simply change the position of the variables
[x, t] = ode45(blablabla)
 

Similar threads

Replies
5
Views
2K
Replies
4
Views
1K
Replies
2
Views
2K
Replies
4
Views
3K
Replies
2
Views
2K
Replies
6
Views
4K
Replies
1
Views
3K
Replies
6
Views
3K
Replies
6
Views
2K
Replies
1
Views
4K
Back
Top