从Matlab函数返回多个输出变量 [英] return multiple output variables from Matlab function
问题描述
让我说我有一个功能:
function [ A, B, C ] = test(x, y, z)
A=2*x;
B=2*y;
C=2*z;
end
按run键时,Matlab仅从输出参数中返回第一个值-在这种情况下为[A]
.我是否可以在函数中放入一条命令,该命令自动返回所有函数输出参数[A,B,C]
而不是仅返回第一个参数.
我知道我可以在命令窗口[ A, B, C ] = test(x, y, z)
中键入并获取所有值,但是有时我很懒,并且只想按Run(运行)并自动获取所有值即可.
When you press run, Matlab returns only the first value from the output arguments - [A]
in this case. Is there a command that I can put inside my function that automatically returns all the function output arguments [A,B,C]
instead of just the first argument.
I know I can type in my command windows [ A, B, C ] = test(x, y, z)
and get all the values, but I am lazy sometimes, and would just like to press Run and get automatically all the values.
推荐答案
某些选项:
添加一个参数以指定控制台的详细输出,但默认情况下将其设置为false:
Add a parameter to specify verbose output the console but set it to false by default:
function [ A, B, C ] = test(x, y, z, verbose)
if nargin = 3
verbose = false;
end;
A=2*x;
B=2*y;
C=2*z;
if verbose
fprintf('A = %f\nB = %f\nC = %f', A, B, C);
end;
end
或将它们合并为一个输出:
or combine them into one output:
function output = test(x, y, z)
A=2*x;
B=2*y;
C=2*z;
output = [A, B, C]; %// Or {A;B;C} if they're not going to be the same size, but then it won't display anyway
end
或者,如果您真的想要,可以编写一个在函数上调用的包装函数,它会为您显示所有可以在任何函数上通用使用的所有三个函数.但这似乎不值得.
or if you really really want to I guess you could write a wrapper function that you call on your function and it displays all three for you that you could use generically on any function. But that hardly seems worthwhile.
这篇关于从Matlab函数返回多个输出变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!