onu*_*tas 2 function return-value octave
为了解决我的问题,让我们考虑最基本的功能
function [x, z] = main ()
x = 1;
z = 2;
endfunction
Run Code Online (Sandbox Code Playgroud)
当我执行此函数时,输出为
ans = 1
而我应该得到类似的东西
ans = 1
2
Run Code Online (Sandbox Code Playgroud)
那为什么会这样呢?问题是什么?
如果您需要Octave(或MATLAB)函数中的多个值,则需要明确询问所有这些值.如果不提供输出参数,则默认行为是仅提供第一个输出(除非用户明确指定不应有输出varargout = {})并将其分配给变量ans.
所以,如果你想两个输出需要明确要求两个人
[x, z] = main()
Run Code Online (Sandbox Code Playgroud)
如果希望函数返回一个数组,x并且z只提供一个输出,则可以nargout用来检测请求了多少输出参数并适当地修改返回值
function [x, z] = main()
x = 1;
z = 2;
% If there is one (or zero) outputs, put both outputs in the first output, otherwise
% return two outputs
if nargout < 1
x = [x; z];
end
endfunction
Run Code Online (Sandbox Code Playgroud)
然后从你的功能之外
main()
% 1
% 2
output = main()
% 1
% 2
[x, z] = main()
% x = 1
% z = 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |