简体   繁体   中英

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

I have vector x = 1:1:100

I have function sin_N(x, iterations) that approximates sin(x) using a summation technique with iterations as the number of terms to compute for the sum. sin_N returns a single number that is the result of the summation.

I want to pass the value x into sin_N so that I get an x length vector where each element is the next step of the summation.

I thought it would look like this (where I am approximating sin(2) in this case):

y2 = sin_N(2, x)

However y2 ends up just being 2.

Can anyone tell me what I'm doing wrong?

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

The function of sin_N is right. It can be used as sin_N(2, 10)--10 times of iteration.

while x is 1:100, you typed sin_N(2,x),MATLAB actually did this : sin_N(2, x(1) (sin_N, 1(the first number of x)

you can check it as :change x into 2:100,the answer of sin_N(2, x) is the same as sin_N(2, 2)

so ,maybe you should try this:

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

The reason why this isn't working is because your function is designed to only output a single number. If you want to output the values at each iteration, you need to declare a vector inside your function, then at each iteration inside the function, you would assign the value at this iteration to the corresponding location in your function. The current iteration is related to the previous iteration, but you add the next term in the series. FWIW, you are actually computing the Maclaurin series for approximating sin .

As such, try something like this instead:

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

To check to see if this works, let's see how sin(2) is calculated after 10 iterations:

y2 = sin_N(2, 10)

This is what I get:

y2 =

 2.0000    0.6667    0.9333    0.9079    0.9093    0.9093    0.9093    0.9093    0.9093    0.9093

As you can see, the value starts to converge at around 0.9093 , which agrees with what sin(2) is approximately equal to:

ytrue = sin(2)

ytrue =

 0.9093

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM