56

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
2
  • 1
    Python has that too. Also, it has numpy, SciPy and more ;) Commented Nov 15, 2010 at 19:45
  • 4
    @Nick please mark the correct answer as correct..... it's been 2 years, the guy deserves his answer to be accepted Commented Nov 9, 2013 at 22:07

4 Answers 4

93

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)
Sign up to request clarification or add additional context in comments.

4 Comments

hmm I thought I tried that and it didn't work, but I guess I forgot the brackets. Thanks!
Also, if you've got a function output variable you don't need, but later ones that you do, the ~ character will avoid wasting memory on a junk variable. For example, [array,~,freep]=initialize(size) (Only in R2009b and later.)
@Nick you may want to consider to accept answer. 5 year is a long time, but I would say better late than never ;).
"seen Dec 8 '10 at 23:29" -- I don't think it'll get accepted :)
0

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.

Comments

-1

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

Comments

-1

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.

1 Comment

This doesn't add anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.