Why does a function that should return 3 vectors arranged in a matrix only return 1 vector?

1 view (last 30 days)
Consider a function:
function [a, b, c] = calculate(d, e, f)
This function should return vectors a, b and c - and as I see it, a, b and c should be arranged in a matrix. However, when I run this function, it returns only one vector! How can this be?

Answers (1)

Matt J
Matt J on 29 Dec 2016
Edited: Matt J on 29 Dec 2016
Call the function with all of its output arguments,
[a, b, c] = calculate(d, e, f);
and then if you want them in a matrix, concatenate as follows
matrix = [a,b,c]
The concatenation can only work if a,b,c are all column vectors of the same length, obviously.
and as I see it, a, b and c should be arranged in a matrix
No idea why you expect that. What if a,b,c are of different lengths? What if they aren't even all vectors? What if some are structs and others are strings? How would you define the concatenation, then?
  2 Comments
Luki
Luki on 29 Dec 2016
allright, thx! It works, when I set up the variable "matrix" and let my function return it. I just figured, since in my function declaration it says:
function [a,b,c] = ...
that [a,b,c] would be the matrix returned by the function.
Image Analyst
Image Analyst on 29 Dec 2016
No, the brackets don't indicate that the 3 outputs will be somehow made into an array, they are just for collecting/indicating that the variables are a group of output arguments that are, or can be returned to the calling routine. It just sort of organizes all the output variables into a part of the line of code to distinguish/separate it from the "function" keyword, the equal sign, the function name, and the list of input arguments. Maybe/perhaps they could have designed the language to do it without the brackets, but for whatever reason they didn't so that's just they way they chose to do it.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!