getting more than one variable back from a function in matlab

To return more than one variable from a MATLAB function, you can use square brackets to create an array of output arguments. For example, if your function needs to return two arrays, you could define the function header like this:

main.m
function [output1,output2] = myFunction(input1,input2)
55 chars
2 lines

Here, output1 and output2 are the two arrays that the function will return. You can use any variable names you like, as long as you separate them with commas within the square brackets.

To return the variables from within the function, simply assign the values to the output arguments using the same syntax. Here's an example function that returns two arrays that are the same size as the input:

main.m
function [out1, out2] = myFunction(in1, in2)
    out1 = in1 + 1;
    out2 = in2 - 1;
end
89 chars
5 lines

In this example, out1 is created by adding 1 to in1, and out2 is created by subtracting 1 from in2. These two arrays are then returned as output from the function. You can call this function and get two outputs like this:

main.m
[a, b] = myFunction(2,3)
25 chars
2 lines

This will set a to 3 (i.e. 2+1) and b to 2 (i.e. 3-1).

gistlibby LogSnag