Problems to be solved in MatLAB 1 The user inputs a vector c
Problems to be solved in MatLAB
1. The user inputs a vector containing positive and negative numbers. Separate the vector into four vectors: posEven, negEven, posOdd and negOdd where posEven contains all the even positive numbers, negEven contains all the negative even numbers, posOdd contains all the positive odd numbers and negOdd contains all the negative odd numbers. Assume 0 is posEven [-50 5 6 -71 26 -25 9 -200 0].
2. Write a function named fact to calculate the factorial of a number.
3.The infinite Maclaurin series to calculate the sine of an angle in radians is:
Write a function, named sine, to calculate the sine of an angle using the above Maclaurin series. Use the fact function created in problem 1 in the sine function. Iterate the terms until the difference between the previous term and the current term is less than 10-5.
4. Write a program that asks for an angle as the input, passes that angle to the sine function, and displays the result to five decimal places as: The sine of ____ is ______.
If 0.3 is entered as the angle, the result would be: The sine of 0.30000 is 0.29552.
Solution
1.
clear
clc
% 4-1 Write a script to solve this problem. Assume you have a vector
% named D. Using iteration (for and/or while) and conditionals (if and/or
% switch), separate vector D into four vectors posEven, negEven, posOdd and
% negOdd.
% posEven contains all of the positive even numbers in D.
% negEven contains all of the negative even numbers in D.
% posOdd contains all of the positive odd numbers in D.
% negOdd contains all of the negative odd numbers in D.
D = [-50 5 6 -71 26 -25 9 -200 0];
posEven = [];
negEven = [];
posOdd = [];
negOdd = [];
for v = D
if v >= 0
if mod(v,2) == 0
posEven = [posEven v];
else
posOdd = [posOdd v];
end
else
if mod(v,2) == 0
negEven = [negEven v];
else
negOdd = [negOdd v];
end
end
end
posEven
negEven
posOdd
negOdd
--------------------------------------------------
--------------------------------------------------
2.
function fact1 = fact(x)
temp = 0;
if (x == 1)
temp = 1;
else
temp = x*fact(x-1);
end
fact1 = temp;
fact1
---------------------------------------------------
---------------------------------------------------
3.
function y = f_sin(x_deg,n)
% x_deg is the argument of the sine function in degrees.
% n is the number of terms used by the series expansion of the sine
% function.
x_rad = degtorad(x_deg); % convert the argument to radians due to the ...
% infinite series uses radians
y = 0;
for j=1:n
y = y + (-1)^(j+1)*(x_rad)^(2*j-1)/fact(2*j-1);
end
end

