how do i obtain several output with a "function" function?
1 view (last 30 days)
Show older comments
Hi everybody, I have a question. My goal is to write a function as the following function[beta] = myfunction (x,y) where beta is a vector k-by-1, x is a n-by-k matrix and y is a n-by-1 vector. Now the length of beta is given by the length k of the x matrix, so its output changes for different length of x. What I want is to save the function and then use it as normal: [beta]=myfunction(x,y) but, instead of showing as result a vector of n elements, I would as output n numbers, one each row of beta, and call them "beta1", "beta2", ... , "beta i". If possible I would not write the code: function[beta1, beta2, ...], since the number of output changes depending on x. How can I write my function?
(If I was not clear in my explaination, what I want is this: [beta]=myfunction(x,y) beta1= .... beta2= .... ... ... beta i= .... )
0 Comments
Answers (2)
James Tursa
on 28 Oct 2014
Edited: James Tursa
on 28 Oct 2014
Please see this related post:
The bottom line is don't do this, it will only create programming headaches downstream for you. Learn to use indexing or cell arrays or some other method that is much friendlier to good programming practices.
3 Comments
James Tursa
on 28 Oct 2014
Edited: James Tursa
on 28 Oct 2014
You can do this using varargout constructs, and programatically return a variable number of outputs. But you would also need to capture these multiple outputs in the calling statement. The specific names beta1, beta2, etc at the calling level would not be determined by your function itself (which would be returning everything in the varargout cell array as varargout{1}, varargout{2}, etc), but would be determined by the calling statement (as is the case with all function calls in MATLAB, no different here) e.g. with an eval statement. Again, I would not advise this. What is the advantage of using beta1, beta2, etc in your code vs simple indexing?
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!