how do i obtain several output with a "function" function?

1 次查看(过去 30 天)
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= .... )

回答(2 个)

Chad Greene
Chad Greene 2014-10-28
An example of varargout is described here.

James Tursa
James Tursa 2014-10-28
编辑:James Tursa 2014-10-28
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 个评论
James Tursa
James Tursa 2014-10-28
编辑:James Tursa 2014-10-28
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?
raffaele
raffaele 2014-10-28
编辑:raffaele 2014-10-28
actually the name doesn't matter much.. I wanted only a way to transform: [beta]=f(x,y) beta =
-0.2496 0.4994 -0.4997 0.3175 -1.4716 0.9725
2.1894 0.2544 8.6052 0.0001 1.5668 2.8120
3.4884 0.3106 11.2301 0.0000 2.7283 4.2484
1.1548 0.6933 1.6658 0.0734 -0.5415 2.8512
into: [beta]=f(x,y)
out1 -0.2496 0.4994 -0.4997 0.3175 -1.4716 0.9725
out2 2.1894 0.2544 8.6052 0.0001 1.5668 2.8120
out3 3.4884 0.3106 11.2301 0.0000 2.7283 4.2484
out4 1.1548 0.6933 1.6658 0.0734 -0.5415 2.8512
It doesn't matter the name of the outputs, I just want to obtain multiple outputs arguments from a single output in square brackets "[...]=function(..)", since, as I've said before, the number of outputs can change depending on x

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by