【问题标题】:Matlab, define y vector by passing each element of x through functionMatlab,通过函数传递x的每个元素来定义y向量
【发布时间】:2014-09-18 01:50:53
【问题描述】:

我有矢量x = 1:1:100

我的函数sin_N(x, iterations) 使用求和技术逼近sin(x),其中迭代作为要计算总和的项数。 sin_N 返回一个作为求和结果的数字。

我想将值 x 传递给 sin_N 以便得到一个 x 长度向量,其中每个元素都是求和的下一步。

我认为它看起来像这样(在这种情况下,我近似于 sin(2)):

y2 = sin_N(2, x)

但是 y2 最终只是 2。

谁能告诉我我做错了什么?

function [sinApprox] = sin_N(sinVal, iters)

newN = sinVal
sinApprox = sinVal
for a=2:iters
    newN = (-1).^(a-1).* abs(newN) .* ((sinVal .^ 2)/((2.*a - 1).*(2.*a-2)))
    sinApprox = sinApprox + newN
end

【问题讨论】:

    标签: matlab function vector


    【解决方案1】:

    这不起作用的原因是因为您的函数设计为只输出一个数字。如果要在每次迭代时输出值,则需要在函数内声明一个 vector,然后在函数内的每次迭代中,将本次迭代的值分配给您的相应位置功能。当前迭代与上一个迭代相关,但您在系列中添加了下一项。 FWIW,您实际上是在计算 Maclaurin series 以逼近 sin

    因此,请尝试以下方法:

    function [sinApprox] = sin_N(sinVal, iters)
    
    newN = sinVal;
    sinApprox = zeros(1,iters); %// NEW
    sinApprox(1) = sinVal; %// Value of the first iteration is sinVal
    for a=2:iters
        newN = (-1).^(a-1).* abs(newN) .* ((sinVal .^ 2)/((2.*a - 1).*(2.*a-2)));
    
        %// NEW - Next iteration is the previous iteration added with newN
        sinApprox(a) = sinApprox(a-1) + newN;
    end
    

    要检查这是否有效,让我们看看在 10 次迭代后如何计算 sin(2)

    y2 = sin_N(2, 10)
    

    这是我得到的:

    y2 =
    
     2.0000    0.6667    0.9333    0.9079    0.9093    0.9093    0.9093    0.9093    0.9093    0.9093
    

    如您所见,该值在0.9093 附近开始收敛,这与sin(2) 约等于:

    ytrue = sin(2)
    
    ytrue =
    
     0.9093
    

    【讨论】:

      【解决方案2】:

      sin_N 的作用是对的。 可以作为sin_N(2, 10)--10次迭代。

      当 x 为 1:100 时, 你输入了 sin_N(2,x),MATLAB 实际上是这样做的:sin_N(2, x(1) (sin_N, 1(the first number of x))

      你可以检查:将x改为2:100,sin_N(2, x)的答案与sin_N(2, 2)相同

      所以,也许你应该试试这个:

      y = zeros(1, 100);
      for x = 1:100
         y(x) = sin_N(2, x)
      end
      

      【讨论】:

      • 次要评论:while 应该是 for 循环。 while x = 1:100 是无效的 MATLAB 语法,因为它需要一个布尔条件。 x = 1:100 不是这样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 2017-11-14
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多