How to put in the fprintf command without data printing limits.

3 views (last 30 days)
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 Comments

Sign in to comment.

Answers (1)

Rik
Rik on 24 Mar 2019
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

Products

Community Treasure Hunt

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

Start Hunting!