how to use nargin function to take variable input arguments and return sum of those arguments
Mostrar comentarios más antiguos
I am not sure how to use the nargin function. I wanted to take a variable number of input arguments and return a sum of those arguments. I am stuck. I have this code so far
function [ output_args ] = addmany() %This function will take zero or more numbers as a variable number of input %arguments and returns the sum of its input arguments. n=nargin; %number of input arguments sum
Not sure how to get a sum of the variable input arguments
4 comentarios
Cedric
el 26 de Oct. de 2013
Is it the statement of a homework, or would you be free to use varargin instead of dealing with nargin?
KayLynn
el 26 de Oct. de 2013
Jan
el 26 de Oct. de 2013
Start with 2 inputs at first to get some experiences with the addition.
Cedric
el 26 de Oct. de 2013
See my answer.
Respuesta aceptada
Más respuestas (1)
it is a statement of homework but there is no specifics as to what commands are able to be used
If there are no restrictions, the better solution would be not to use separate arguments at all. Just put all arguments in a vector x and do sum(x).
function y = addmany(x)
y=sum(x);
end
>> y=addmany([1 2 3 4])
y =
10
2 comentarios
KayLynn
el 26 de Oct. de 2013
Doesnt addmany(x) only add one of the inputs.
Yes, but it's not clear why the summands have to be passed as separate input arguments rather than as elements of one single vector. Was that a requirement of the homework assignment?
or is there something I can do to take any variable number of inputs and find the sum of them
Yes, there is a way, and Cedric gave you strong hints. Here is another small one
Categorías
Más información sobre Argument Definitions en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!