How to take variable number of inputs arugments and return their sum

1 次查看(过去 30 天)
I am trying to write a functin addmany.m that takes zero or more numbers as a variable number of input arguments and returns the sum of its input arguments. I am trying to use the narargin and varargin commands. I have the following code written:
function [y] = main(varargin)
%This function will take zero or more numbers as a variable number of input
%arguments and returns the sum of its input arguments.
switch nargin
case 0
disp('0 inputs given')
alpha = 10 %default value
beta = 10 %default value
case 1
disp('1 inputs given')
alpha = varargin{1}
beta = 10 %default value
case 2
disp('2 inputs given')
alpha = varargin{1}
beta = varargin{2}
otherwise
error('Unexpected inputs')
end
y= alpha + beta;
I am trying to get the following result Input is 1,10,100 Output is 111.
If you could please tell me which line/part is wrong and what it should be, I would appreciate it

采纳的回答

Image Analyst
Image Analyst 2013-10-29
Try this:
function theSum = AddMany(varargin)
theSum = []; % Initialize
if nargin == 0
uiwait(warndlg('Please input 1 or more numbers'));
return;
end
fprintf('Number of arguments: %d\n',nargin);
celldisp(varargin)
inputNumbers = cell2mat(deal(varargin))
theSum = sum(inputNumbers);
  13 个评论
Daniel Shub
Daniel Shub 2013-10-29
I am pretty sure with squiggly brackets {} you get an array of doubles and with smooth brackets () you get a cell array. So with {} it seems to work
x = {1, 2, 3};
sum([x{:}])

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by