Function MatLab-nargout

Function MatLab-nargout,function,matlab,Function,Matlab,我正在自学MatLab,书中有一个作业我不太明白。基本上,我正在编写一个函数,通过使用泰勒级数计算正弦。到目前为止,我的代码如下: 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

我正在自学MatLab,书中有一个作业我不太明白。基本上,我正在编写一个函数,通过使用泰勒级数计算正弦。到目前为止,我的代码如下:

    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
函数y=sine_系列(x,n); %正弦级数:从级数展开计算sin(x) %x可以作为向量输入,以允许同时进行多个计算
如果n调用
nargout
检查调用函数的输出参数数量。根据
nargout
的大小,您可以将条目分配给输出参数
varargout
。对于您的代码,这看起来像:

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


查看差异。

调用
nargout
检查调用函数时使用的输出参数的数量。根据
nargout
的大小,您可以将条目分配给输出参数
varargout
。对于您的代码,这看起来像:

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


看看有什么不同。

太棒了!谢谢。现在我明白了。我真的很感激。太棒了!谢谢。现在我明白了。我真的很感激。
[y err] = sine_series(rand(1,10),3)