簡體   English   中英

Matlab,通過將x的每個元素傳遞給函數來定義y向量

[英]Matlab, define y vector by passing each element of x through function

我有向量x = 1:1:100

我有函數sin_N(x, iterations) ,該sin(x)使用求和技術將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

sin_N的功能是正確的。 它可以用作sin_N(2,10)-10次迭代。

當x為1:100時,您鍵入sin_N(2,x),MATLAB實際上是這樣做的:sin_N(2,x(1)(sin_N,1(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

之所以不起作用,是因為您的函數只能輸出一個數字。 如果要在每次迭代中輸出值,則需要在函數內部聲明一個向量 ,然后在函數內部的每次迭代中,都需要將此迭代中的值分配給函數中的相應位置。 當前迭代與上一個迭代相關,但是您要在系列中添加下一個術語。 FWIW,您實際上是在計算Maclaurin系列以近似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

為了檢查它是否有效,讓我們看看如何在十次迭代后計算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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM