# [Solved] MatLab – nargout

I am learning MatLab on my own, and I have this assignment in my book which I don’t quite understand. Basically I am writing a function that will calculate sine through the use of Taylor series. My code is as follows so far:

``````    function y = sine_series(x,n);
%SINE_SERIES: computes sin(x) from series expansion
% x may be entered as a vector to allow for multiple calculations simultaneously
if n <= 0
error('Input must be positive')
end
j = length(x);
k = [1:n];
y = ones(j,1);
for i = 1:j
y(i) = sum((-1).^(k-1).*(x(i).^(2*k -1))./(factorial(2*k-1)));
end
``````

The book is now asking me to include an optional output `err` which will calculate the difference between sin(x) and y. The book hints that I may use `nargout` to accomplish this, but there are no examples in the book on how to use this, and reading the MatLab help on the subject did not make my any wiser.

## Solution #1:

The call to `nargout` checks for the number of output arguments a function is called with. Depending on the size of `nargout` you can assign entries to the output argument `varargout`. For your code this would look like:

``````function [y varargout]= sine_series(x,n);
%SINE_SERIES: computes sin(x) from series expansion
% x may be entered as a vector to allow for multiple calculations simultaneously
if n <= 0
error('Input must be positive')
end
j = length(x);
k = [1:n];
y = ones(j,1);
for i = 1:j
y(i) = sum((-1).^(k-1).*(x(i).^(2*k -1))./(factorial(2*k-1)));
end
if nargout ==2
varargout{1} = sin(x)'-y;
end
``````

Compare the output of

``````[y] = sine_series(rand(1,10),3)
``````

and

``````[y err] = sine_series(rand(1,10),3)
``````

to see the difference.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .