1

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.

If anyone can please help me understand this, I would really appreciate it!

Kristian
  • 1,239
  • 12
  • 31
  • 44

1 Answers1

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.

H.Muster
  • 9,297
  • 1
  • 35
  • 46