MATLAB - multiple return values from a function?

MatlabReturn Value

Matlab Problem Overview


I'm writing 2 functions in matlab, an initialize function and a function to insert items into an array treating it like a doubly-linked list. However, my initialize function only returns "ans =" and the initialized array. How can I have it also set values of my other variables? Here's my code:

function [ array, listp, freep ] = initialize( size )
    array = zeros(size, 3);
    listp = 0;
    freep = 1;
end

Matlab Solutions


Solution 1 - Matlab

Matlab allows you to return multiple values as well as receive them inline.

When you call it, receive individual variables inline:

[array, listp, freep] = initialize(size)

Solution 2 - Matlab

I think Octave only return one value which is the first return value, in your case, 'array'.

And Octave print it as "ans".

Others, 'listp','freep' were not printed.

Because it showed up within the function.

Try this out:

[ A, B, C] = initialize( 4 )

And the 'array','listp','freep' will print as A, B and C.

Solution 3 - Matlab

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Solution 4 - Matlab

Use the following in the function you will call and it will work just fine.

     [a b c] = yourfunction(optional)
     %your code
     a = 5;
     b = 7;
     c = 10;
     return
     end

This is a way to call the function both from another function and from the command terminal

     [aa bb cc] = yourfunction(optional);

The variables aa, bb and cc now hold the return variables.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNickView Question on Stackoverflow
Solution 1 - MatlabMikhailView Answer on Stackoverflow
Solution 2 - MatlabFranciView Answer on Stackoverflow
Solution 3 - MatlabValdivia FernandoView Answer on Stackoverflow
Solution 4 - MatlabFthi.a.AbadiView Answer on Stackoverflow