write a script which will calculate the value of cos(x) (ask the user for the value of x and n) : ( ) ∑( ) = − − − = − + − = − n k k k k x x x x 1 2( 1) 1 2 4 2( 1)! in matlab

main.m
% ask user for the value of x and n
x = input('Enter the value of x: ');
n = input('Enter the value of n: ');

% initialize variables
cosine = 1;
factorial_term = 1;

% calculate the value of cosine with the given formula
for k = 1:n
    factorial_term = factorial_term * (2*k-1) * 2*k;
    % successive terms are alternately added and subtracted
    if mod(k, 2) == 0
        cosine = cosine - ((x^(2*k))/factorial_term);
    else
        cosine = cosine + ((x^(2*k))/factorial_term);
    end
end

% display the final result
fprintf('The value of cosine of %f is %f\n', x, cosine);
583 chars
22 lines

Note: this code uses the formula provided in the question that calculates cos(x) with the value of n_terms.

gistlibby LogSnag