问题描述
matlab中是否有一种方法可以将matlab中的函数的输出分配给一行中的向量?
Is there a way in matlab to assign the output from a function in matlab to a vector within a single line?
例如,此函数应指定周长和面积值
For example, this function should assign a perimeter and an area value
function [p,a] = square_geom(side)
p = perimeter_square(side)
a = side.^2
[p,a]
但是,当我尝试存储这样的数据时
however when I try to store the data like this
v = square_geom(3)
它不起作用.但是,可以这样做
It doesn't work. However it is possible to do it like this
[p,a] = square_geom(3)
v=[p,a]
但这看起来不如将其保持为一行.有什么想法吗?
But that just doesn't look as good as keeping it to a single line. Any ideas?
推荐答案
您可以使用varargout
作为输出变量来更改函数的定义:
You can change the definition of your function by using varargout
as output variable:
修改更新了函数的定义,以包括对输出数量的检查
EditUpdated the definition of the function to include the check on the number of output
function varargout = square_geom(side)
p = 3;% %perimeter_square(side)
a = side.^2;
v=[p,a];
switch(nargout)
case 0 disp('No output specified, array [p,a] returned')
varargout{1}=v;
case 1 varargout{1}=v;
case 2 varargout{1}=p;
varargout{2}=a;
case 3 varargout{1}=v;
varargout{2}=p;
varargout{3}=a;
otherwise disp(['Error: too many (' num2str(nargout) ') output specified'])
disp('array [p,a,NaN, NaN ...] returned (NaN for each extra output)')
varargout{1}=v;
varargout{2}=p;
varargout{3}=a;
for i=4:nargout
varargout{i}=NaN
end
end
这允许您以几种方式调用函数
This allows you either calling your function in several ways
square_geom(3)
v=square_geom(3)
[a,b]=square_geom(3)
[a,b,d]=square_geom(3)
[a,b,d,e,f,g]=square_geom(3)
在第一种情况下,将数组v
作为自动变量ans
In the first case you get the array v
as the automatic variable ans
square_geom(3)
No output specified, array [p,a] returned
ans =
3 9
在第二种情况下,获得数组v
In the second case, you get the array v
v=square_geom(3)
v =
3 9
在第三种情况下,您将获得两个变量
In the third case, you get the two variables
[a,b]=square_geom(3)
a = 3
b = 9
在第四种情况下,您将获得数组v
和两个sigle变量a
和b
In the fourth case, you get the array v
and the two sigle variables a
and b
[v,b,d]=square_geom(3)
v =
3 9
b = 3
d = 9
在后一种情况(指定的输出太多)中,您将获得数组v
,两个单个变量a
和b
以及超出的变量(e
,f
和g
)设置为NaN
In the latter case (too many output specified), you get the array v
, the two single variables a
and b
and the exceeding variables (e
, f
and g
) set to NaN
[v,b,d,e,f,g]=square_geom(3)
Error: too many (6) output specified
array [p,a,NaN, NaN ...] returned (NaN for each extra output)
v =
3 9
b = 3
d = 9
e = NaN
f = NaN
g = NaN
注意,到目前为止,我已经通过用3
Notice, to thest the code I've modified the function byh replacing the call toperimeter_square
with 3
这篇关于如何在单行中将Matlab函数的输出分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!