MatLab - nargout [英] MatLab - nargout

查看:83
本文介绍了MatLab - nargout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 函数y = sine_series(x,n); 
%SINE_SERIES:从系列扩展计算sin(x)
%x可以作为一个向量输入以允许同时进行多个计算
如果n <= 0
错误('输入必须是正数')
end
j = length(x);
k = [1:n];
y = ones(j,1); (i)= sum(( - 1)。^(k-1)。*(x(i)。^(2 * k-1)).//
for i = 1: (阶乘(2 * K-1)));
end

本书现在要求我包含一个可选输出 err 这将计算sin(x)和y之间的差异。本书提示我可以使用 nargout 来实现这一点,但是在书中没有关于如何使用它的例子,并且阅读MatLab对这个主题的帮助没有做出我的任何智慧。



如果有人能够帮助我理解这一点,我真的很感激它!

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

  function [y varargout] = sine_series(x,n); 
%SINE_SERIES:从系列扩展计算sin(x)
%x可以作为一个向量输入以允许同时进行多个计算
如果n <= 0
错误('输入必须是正数')
end
j = length(x);
k = [1:n];
y = ones(j,1); (i)= sum(( - 1)。^(k-1)。*(x(i)。^(2 * k-1)).//
for i = 1: (阶乘(2 * K-1)));
end
如果nargout == 2
varargout {1} = sin(x)' - y;
end

比较

的输出

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



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

查看差异。

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!

解决方案

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.

这篇关于MatLab - nargout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆