问题
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?
回答1:
You can change the definition of your function by using varargout as output variable:
Edit Updated 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)
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
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
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
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
Notice, to thest the code I've modified the function byh replacing the call toperimeter_square with 3
回答2:
The value outputted by the function are two different variables, not an array. So the output should be stored as two cells.
[v(1),v(2)]=fn(val)
Here, the value is stored in two different cell v(1) and v(2) of the same array 'v'.
回答3:
The simplest solution that comes into my mind is:
c = test();
function result = test()
a = ...; % complex computation
b = ...; % complex computation
result = [a b];
end
The C variable will then be a column vector containing two values. But this solution is only suitable if your function output doesn't need to be flexible.
回答4:
You can get your multiple outputs in a cell array.
In your case:
v=cell(1,2);
[v{:}]=square_geom(3)
来源:https://stackoverflow.com/questions/48671058/how-do-i-assign-the-output-from-a-matlab-function-to-a-variable-in-a-single-line