is it ok to have a function where the input is the output

i have a function where the "ebatt" is an array of numbers and every number of this array depends on it's predecessor : as it follows :
function [ebatt,epg,dps]= chargebatt(ebatt,i,sigmma,epv,ech,Rond,rbatt,Ebattmax)
ebatt(i) = ebatt(i-1).*(1-sigmma)+(epv(i)-ech(i))/Rond;
if ebatt(i)> Ebattmax
epg(i)= epv(i)-(ech(i)./Rond+(Ebattmax-ebatt(i-1))/rbatt);
ebatt(i) = Ebattmax;
dps(i) = 0;
else
epg(i) =0;
dps(i) =0;
end
is it ok to put the output of this function the same as the input ebatt

 Accepted Answer

Yes.
function x=myfun(x)
% stuff
end
is entirely valid. A little on the boring side, but...

More Answers (2)

And what if all my Inputs are also my Outputs? Like:
function [a,b,c]=myfun(a,b,c)
a=b+c
b=a-c
c=a-b
end
I don't know what I get for Inputs and that's why I can't give a,b and c. I know that there is a function named "vargin" and "vargout".
How can I execute this problem?

3 Comments

For an unknown number of inputs and the same number of outputs use varargin and varargout:
function varargout = fun(varargin)
varargout = varargin;
end
But this is going to be very awkward to use, as specifying all of those separate inputs and outputs makes the code complex and liable to bugs. Most likely you would be much better off storing all of that data in one array (or some arrays), and then just passing that array.
Splitting data into lots of separate variables is what beginners do when they want to force themselves into writing slow, buggy, complex code. Keeping data together as much as possible makes code simpler and more reliable.
I have to split my variables, because I have to integrate this function in Cameo System Modeler and this program needs defind variables. So, is there maybe another way? I'm also not sure that I can hand arrays to the matlab function over.
"So, is there maybe another way?"
To do what? I already showed you how to write a function accept and return an arbitrary number of arguments, and advised you that passing arrays is likely simpler. That covers the two possible cases using input/output arguments.
You could trivially avoid the whole problem by using nested functions:

Sign in to comment.

A nice function, which has at least a use, is the swapping of two variables:
function [b, a] = swap(a, b)
% This function does not have a body!
end

1 Comment

Reversing an arbitrary number of arguments with an anonymous function:
>> rev = @(varargin)varargin{end:-1:1};
>> [a,b,c] = rev(1,2,3)
a = 3
b = 2
c = 1

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!