have a function that returns multiple values, but only use one of them? in matlab

In Matlab, you can return multiple values from a function by separating them with commas. If you only want to use one the output variables, you can use the tilde (~) character to indicate that you don't intend to use that value. Here is an example function that returns three outputs but only the first is used:

main.m
function [output1, output2, output3] = myFunction(input1, input2)
    % some computations 
    output1 = input1 + input2;
    output2 = input1 - input2;
    output3 = input1 * input2;
end
188 chars
7 lines

To use only the first output, you can call the function and assign the outputs like this:

main.m
result = myFunction(2, 3); % returns 5, -1, 6
value = result(1); % assigns the first output (5) to the variable "value"
120 chars
3 lines

Alternatively, you can use the tilde to indicate that you don't care about the other outputs:

main.m
[value, ~, ~] = myFunction(2, 3); % assigns only the first output (5) to "value"
81 chars
2 lines

Note that using the tilde character can be useful if you want to ignore some outputs but still want to maintain the correct number of output arguments.

related categories

gistlibby LogSnag