Subfunction with output varargout returns only first element of cell array. Why?

2 ビュー (過去 30 日間)
Pal Szabo
Pal Szabo 2017 年 8 月 31 日
編集済み: Matt J 2017 年 8 月 31 日
This is my script:
a=9;
b=2;
[varargout] = myfunc(a,b)
c=varargout
function [varargout] = myfunc(a,b)
sum=a+b;
dif=a-b;
prod=a*b;
varargout={sum,dif,prod}
end
After execution, the value of c is 11. I want it to be an array, with values 11, 7, 18. {sum, dif,prod}. What is wrong with my script, and how can I get the desired array?

採用された回答

Matt J
Matt J 2017 年 8 月 31 日
編集済み: Matt J 2017 年 8 月 31 日
I you only want all the computations bundled into one output argument, then varargout is not the right thing:
function c = myfunc(a,b)
sum=a+b;
dif=a-b;
prod=a*b;
c={sum,dif,prod};
  3 件のコメント
Matt J
Matt J 2017 年 8 月 31 日
編集済み: Matt J 2017 年 8 月 31 日
In that case, your original code is correct, but you need to call myfunc with more output arguments
sum=myfunc(dif)
or
[sum,dif] = myfunc(a,b)
or
[sum,dif,prod] = myfunc(a,b)
If you want a single output array but containing variable amounts of data, you have to control that through the input arguments,
function out = myfunc(a,b, howmany)
sum=a+b;
dif=a-b;
prod=a*b;
c={sum,diff,prod};
out=c(1:howmany);
Pal Szabo
Pal Szabo 2017 年 8 月 31 日
Now it works. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by