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

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

HINT: Move the initial text line outside the loop...then what would you do next to create the desired output?
BTW; you're missing a newline on the <1 case...
Or, alternatively, what if you had all the inputs in a single array?
Hi, I do not understand very well what you say. In the first thing you say, what do I have to get out of the loop specifically? What line is missing in the case <1? Thank you very much for your help.
You missed a \n (newline) for the "no numbers" case.
Oh yes, I see it. What else is needed to make the program work?
Act on the hints I gave you earlier...

Sign in to comment.

Answers (1)

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

Answered:

Rik
on 24 Mar 2019

Community Treasure Hunt

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

Start Hunting!