How to put in the fprintf command without data printing limits.
조회 수: 1 (최근 30일)
이전 댓글 표시
I am trying to solve the following problem:
Write a function called print_all that takes any number of scalar input arguments (the function does not need to check the format of the input) and prints them out one by one as illustrated by a few runs:
>> print_all()
We received no numbers.
>> print_all(34)
We received the following number: 34.
>> print_all(34, 56, 78, 90)
We received the following numbers: 34, 56, 78, and 90.
Make sure that the function handles the three cases (no input, one input, more than one input) correctly, as illustrated above. The function has no output arguments.
I have tried to do the following but I can not make the step where the fprintf goes more than two outputs, that is, when the function has more than two inputs
function print_all(varargin)
if nargin<1
fprintf('We received no numbers.');
elseif nargin==1
fprintf('We received the following number: %f \n',varargin);
else
for i=1:nargin
fpirntf('We received the following numbers:')
end
end
end
What can I do to complete or fix my function? Thank you very much for the help.
댓글 수: 5
답변 (1개)
Rik
2019년 3월 24일
Normally I am opposed to providing turn-key solutions to homework, but in this case I feel that the best way to explain is to show the code. See the comments for my edits to your code.
function print_all(varargin)
if nargin<1
fprintf('We received no numbers.\n');%added \n
elseif nargin==1
fprintf('We received the following number: %f \n',varargin);
else
fprintf('We received the following numbers:');%corrected typo in function name
for n=1:nargin%avoid i an j as loop iterators, as they can cause confusion with sqrt(-1)
fprintf(' %f',varargin{n});
end
fprintf('\n');
% %alternatively, as dpb suggested:
% fprintf('We received the following numbers:');
% fprintf(' %f',varargin{:});
% fprintf('\n');
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!