필터 지우기
필터 지우기

Problem with multiple inputs

조회 수: 1 (최근 30일)
Czarek Czarek
Czarek Czarek 2021년 2월 15일
댓글: Czarek Czarek 2021년 2월 15일
function varargout = Untitled(a,varargin)
varargout{1}=0;
if (a=='+')
disp('Add');
for i=1:nargin
varargout{1} = varargout{1} + varargin{i};
i=i+1;
disp(varargout{1});
end
end
end
when i put commadn in cosole program add number in loop, but next throw error
>> Untitled('+',3,3,4,10)
Add
3
6
10
20
Index exceeds the number of array elements (4).
Error in Untitled (line 11)
varargout{1} = varargout{1} + varargin{i};
And when i put disp(varargout{1}) outside loop program dont throw outputs. pls help

채택된 답변

Jan
Jan 2021년 2월 15일
편집: Jan 2021년 2월 15일
for i=1:nargin
nargin is the number of all inputs. For Untitled(a,varargin) thenumber of inputs is 1 larger than the size of varargin.
Try:
for i = 1:numel(varargin)
% or
for i = 1:nargin - 1
Hint: Omit the "i=i+1", which is useless. The loop counter is increased by the for command. It does not produce an error here, because i is not used after this line, but it is confusing. See
for k = 1:5
fprintf('k = %d\n', k);
k = k + 1000;
fprintf('modificed k = %d\n', k);
end
  댓글 수: 1
Czarek Czarek
Czarek Czarek 2021년 2월 15일
for i = 1:nargin - 1 this is answer for my question
i figured it out couple minut ago by display nargin on board :p, but thank you very much for help <3

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by