Matlab For Applied Math

Matlab For Applied Math

Β·

27 min read

Applied Math

Various Example:

Write a function, that returns 𝑆n for a given 𝑛, where

image

function S=solve(n)
    k = 1:n;
    S = sum(1./k);
end

Write a function, that returns 𝑆n for a given 𝑛, where

image

function S=solve(n)
    k = 1:n;
    S = sum(((-1).^(k+1))./k);
etnd

Write a function, that returns for a given 𝑛 the 𝑛x𝑛 version of the matrix below.

image

function A=solve(n) 
    l=0; 
        for i = 1:n 
            for j = 1:n 
                l=l+1; 
                A(i,j)=l; 
            end 
        end
    for k=2:2:n 
        A(k,:)=flip(A(k,:)); 
    end 
end

Write a function, that returns the 𝑛x𝑛 version of the matrix below.

image

function A=solve(n) 
    A = flip(eye(n)); 
end

Write a function, that returns for a given 𝑛 the 𝑛 x 𝑛 version of the matrix below.

image

function A = solve(n) 
    A = ones(n);
    for i = 2:n-1 
        for j = 2:n-1 
            A(i,j)=0; 
        end 
    end 
end

Write a function, that returns for a given 𝑛 the 𝑛x𝑛 version of the matrix below.

image

function A = solve(n) A = zeros(n); 
    for i = 1:n 
        for j = 1:n 
            if mod(i, 2) == 0
                if mod(j, 2) ~= 0 
                    A(i, j) = -1; 
                else
                    A(i, j) = 1; 
                end
            else 
                if mod(j, 2) ~= 0 
                    A(i, j) = 1; 
                else
                    A(i, j) = -1; 
                end 
            end
        end
    end
end

Floats 1:

The normalized, regularly rounded representation of the number 3/40 in the floating point system F=[a=2, k-=-6, k+=6, t=4] is:

[b,ex] = float2bin(3/40,4)

In the floating point number system F=[a=2, k-=-5, k+=4, t=6] the the normalized, choped representation of 0.520 is:

[b,ex] = float2bin(0.520,6)

In the floating point number system F=[a=2, k-=-4, k+=3, t=6] the the normalized, choped representation of 23/49 is:

[b,ex] = float2bin(23/49,6)

In the floating point number system F=[a=2, k-=-4, k+=3, t=6] the quantities 𝑀inf, 1-, E1 are:

a = 2;
k_minus = -4;
k_plus = 3;
t = 6;
format rational
M_inf = (a^k_plus)*(1-a^(-t));
E0 = a^(k_minus-1);
E1 = a^(1-t);
one_plus = 1 + (a^(1-t));
one_minus = 1 - (1/(a^t)); 
n = (k_plus - k_minus + 1 ) * a^(t-1);
smallest_int = a^(t+1);
smallest_int_not_in_F = (a^t)+1

Floats 2():

Consider the floating point system F=[a=2, k-=-10, k+=10, t=7] The smallest positive integer that is not in F is:

a = 2;
k_minus = -10;
k_plus = 10;
t = 7;
format rational
M_inf = (a^k_plus)*(1-a^(-t));
E0 = a^(k_minus-1);
E1 = a^(1-t);
one_plus = 1 + (a^(1-t));
one_minus = 1 - (1/(a^t)); 
n = (k_plus - k_minus + 1 ) * a^(t-1);
smallest_int = a^(t+1);
smallest_int_not_in_F = (a^t)+1

Consider the floating point system F=[a=2, k-=-6, k+=5, t=5] The right-neighbour of 13/512 is:

a = 2;
t = 5;
g_val=13/512;
format long
[b,ex] = float2bin(g_val,t);
distance_right_neighbor = a^(ex-t)
distance_left_neighbor = a^(ex - t)
right_neighbor = g_val + distance_right_neighbor
left_neighbor = g_val - distance_left_neighbor

Consider the floating point system F=[a=2, k-=-6, k+=5, t=4] The distance between 9/1024 and its left-neighbour is:

a = 2;
t = 4;
g_val=9/1024;
format long
[b,ex] = float2bin(g_val,t);
distance_right_neighbor = a^(ex-t)
distance_left_neighbor = a^(ex - t)
right_neighbor = g_val + distance_right_neighbor
left_neighbor = g_val - distance_left_neighbor

cond 1:

if

image

then condinf (A):

A = [-8 2 8;0 4 2;-5 4 6];
cond_inf_A = cond(A, 'inf')

if

$$X = \begin{bmatrix} 4 & -2 & -3 & 10\\ -9 & 3 & -3 & -7\\ 6 & -10 & 5 & 0\\ 6 & -10 & 0 & 8\\ \end{bmatrix}$$

then the approximate values of cond1(𝐴), condinf(𝐴) and cond2(𝐴) are respectively:

A = [4 -2 -3 10; -9 3 -3 -7; 6 -10 5 0; -6 -10 0 8];
cond_inf_A = cond(A, 'inf')
cond_1_A = cond(A, 1)
cond_2_A = cond(A, 2)

Norms 1:

if

image

then ||𝐴||inf, ||𝐴||1 and ||𝐴||2 are respectively:

A = [-10 -6 5; -8 -4 2; -2 -8 4];
norm_inf_A = norm(A, 'inf')
norm_1_A = norm(A, 1)
norm_2_A = norm(A, 2)

if X = [6, -3, -10, 3, 2] then ||X||1, ||X||2 and ||X||inf is respectively:

X = [6 -3 -10 3 2] 
norm_inf_X = norm(X, 'inf')
norm_1_X = norm(X, 1)
norm_2_X = norm(X, 2)

For the vectors

X = [βˆ’9 0 1 9 5] Y = [9 9 βˆ’10 βˆ’3 4] Z = [βˆ’3 βˆ’7 βˆ’9 βˆ’8 βˆ’2 βˆ’4]

choose the correct ordering for ||X||5, ||Y||10 and ||Z||2:

X = [-9 0 1 9 5];
Y = [9 9 -10 -3 4];
Z = [-3 -7 -9 -8 -2 -4];
norm_5_X = norm(X, 5)
norm_10_Y = norm(Y, 10)
norm_2_Z = norm(Z, 2)

Code 1:

x=[7, -1, -4, -3, -2, 4, 6];
for i=2:7
  x(i)=3+x(i)+x(i-1)
end

After executing the code above the value of x(7) is: the sum of the elements of x is:

A = x(7)
S = sum(x)
x=[-5, 5, -6, -6, 1, -5];
for i=2:5
  x(i)=-2+2*x(i-1)+x(i)+2*x(i+1)
end

After executing the code above the value of x(5) is: the sum of the elements of x is:

A = x(5)
S = sum(x)
x=[-6, -2, 2, -2, 2, -3, 1];
for i=3:7
  x(i)=3+x(i-1)+2*x(i-2)
end
A = x(5)
B = x(7)

Linsys 1:

Consider the Cholesky-decomposition of the matrix (LLT)

image

A = [1 -2 1; -2 5 -4; 1 -4 9];
L_transpose = chol(A)
L = L_transpose'

For the matrix 𝐴 we know partially its Cholesky-decomposition:

image

Then the value of 𝑋 is: the value of π‘Œ is:

A = [25 15 10 5; 15 13 8 13; 10 8 30 27; 5 13 27 46];
L_transpose = chol(A)
L = L_transpose'

Consider the LU decomposition of the matrix

image

Then

https://www.emathhelp.net/en/calculators/linear-algebra/lu-decomposition-calculator/

image

In the LU decomposition of the matrix

image

the elements L32and U33:

https://www.emathhelp.net/en/calculators/linear-algebra/lu-decomposition-calculator/

image

Once we have the 𝐴=πΏπ‘ˆ decomposition, the usual way to solve the 𝐴π‘₯=𝑏 equation is to solve 𝐿𝑦=𝑏 for 𝑦and π‘ˆπ‘₯=𝑦 for π‘₯. Triangular systems can be solved by the back-substitution. For a given decomposition

image

and a constant vector (right hand side) b^T =[βˆ’18 74 50] apply the method of back-substitution. Then the value of X2 is: and the value of Y3 is:

L = [1 0 0; -4 1 0; -3 1 1];
U = [-4 2 1;0 3 4;0 0 -3];
b = [-18 74 50]';
y = linsolve(L, b)
x = linsolve(U, y)
x_2 = x(2)
y_3 = y(3)

For the matrix 𝐴 we know partially its πΏπ‘ˆ decomposition:

image

Then the value of 𝑋 is: the value of π‘Œ is: the value of det(𝐴) is:

https://www.emathhelp.net/en/calculators/linear-algebra/lu-decomposition-calculator/

image

det_A = det(A)
% OR
% product of Diagonal of U

Noloop:

Write a function that computes and returns the value of

image

Additional information: 0 ≀ 𝑛 ≀ 20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
    k=0:n;
    R=prod(1-(sin(k)./(k+1)));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"]based constructs.

function R=solveit(n)
k = 1:n;
R = prod(1 - (1./(2.^k)));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs

function R=solveit(n)
k = 0:n;
R = prod(((5.*k)+1)./((k.^2)+1));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 1:n;
R = prod(cumsum(k./((k.^2)+1)));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 1:n;
R = prod(cumsum(((-1).^k)./k));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
    k = 0:n;
    R = sum(1./(factorial(k)));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 0:n;
R = sum(1./(k+1));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 0:n;
R = sum((k+1)./((k.^2)+1));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 0:n;
R = sum((sin(k+1))./(k+1));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 0:n;
R = sum(((k.^3)+1)./(e.^k));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 1:n;
R = sum(cumprod((k)./(((k).^2)+1)));
end

Write a function that computes and returns the value of

image

Additional information: 0≀𝑛≀20 For this problem it is forbidden to use ["for", "while", "do", "until"] based constructs.

function R=solveit(n)
k = 2:n;
R = sum(cumprod((1+(((-1).^(k))./(k))).^(k)));
end

lsquares 1:

In the sense of the least squares method, what the best fitting line for the data below?

image

t = [1 7 0 4 -2 2];
f = [-4 2 -6 -3 2 -8];
format rat
polyfit(t,f,1)

image

Using the least squares method, we approximated the data given below by a line. Which of the plots above represents correctly the data and the best line?

image

% Compare the points with charts and the answer is β€œA”

Consider the best fitting line for the data below. Then its value at βˆ’13/2 is

image

t = [-10 5 7 5 9 8 -3]; 
f = [-10 -6 8 -7 -8 -8 3];
p = polyfit(t,f,1);
polyval(p, -13/2)

In the sense of the least squares method, what the best fitting second order polynomial for the data below?

image

t = [-2 0 3 2 -2 2 -3];
f = [8 -9 -4 5 -10 4 -1];
polyfit(t,f,2)

Consider the best fitting second order polynomial for the data below. Then its value at βˆ’10 is

image

t = [2 -4 -8 5 7 8 4];
f=[2 1 -9 6 1 4 7];
p = polyfit(t,f,2);
format long
polyval(p, -10)

In the sense of the least squares method, what the best fitting function of the form (π‘Ž/𝑑 + 𝑏) for the data below?

image

t = [6, 9, 9, 9, 6, 6]';
f = [5, 3, 7, 10, 6, 5]';
A = [1./t ones(length(t), 1)];
a1 = A' * A;
f1 = A' * f;
x = a1\f1

Consider the best fitting function of the form (π‘Ž/𝑑 + 𝑏) for the data below.

image

Then its value at βˆ’19/2 is

t = [1, -9, -9, -3, -9, -5]';
f = [2, -2, 8, -5, 3, 3]';
A = [1./t ones(length(t), 1)];
a1 = A' * A;
f1 = A' * f;
x = a1\f1
(x(1)/(-19/2)) + x(2)

In the sense of the least squares method, what the best fitting function of the form (𝑓(𝑑)=π‘Žsin(πœ‹π‘‘)+𝑏) for the data below?

image

format rat
t = [21/2 6 14 33/2 2 31/2]';
f = [1 3 -9/2 -9/2 3 -2]';
A = [sin(pi*t) ones(length(t), 1)];
a1 = A' * A;
f1 = A' * f;
x = a1\f1

Evaluate at βˆ’11/2 the best approximating (in the sense of least squares) 𝑓 function of type (𝑓(𝑑)=π‘Žcos(πœ‹π‘‘)+𝑏) for the data below.

image

format default
t = [1 13/2 -6 -3 5 1/2 1/2]';
f = [-5 1/2 3 -2 -5 -3/2 -9/2]';
A = [cos(pi*t) ones(length(t), 1)];
a1 = A' * A;
f1 = A' * f;
x = a1\f1
x(1)*cos(pi*(-11/2)) + x(2)

lsquares 2():

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for a function 𝐹(𝑑)=π‘Žπ‘‘+𝑏 that fits best the data in the sense of the least squares method. Write a function, that returns π‘π‘Žπ‘Ÿπ‘ =(π‘Ž,𝑏) and 𝑦=(𝐹(π‘₯1),...,𝐹(π‘₯n)) for parameters 𝑑,𝑓,π‘₯. Additional information: 3β‰€π‘šβ‰€10 2≀𝑛≀5 In each of the cases the solution is uniquely determined by the data.

function [pars,y]=solve(t,f,x)
p = polyfit(t, f, 1);
a = p(1);
b = p(2);
y = polyval(p, x);
pars = [a, b];
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for the slope and the constant term of the line that fits best the data in the sense of the least squares method. Write a function, that returns π‘Ž,𝑏,𝑦, where π‘Ž is the slope, 𝑏 is the constant term of the needed line and 𝑦=π‘Žπ‘₯+𝑏. Additional information: 3β‰€π‘šβ‰€10 In each of the cases the solution is uniquely determined by the data.

function [a,b,y]=solve(t,f,x)
    p = polyfit(t, f, 1);
    a = p(1);
    b = p(2);
    y = a*x + b;
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for the slope and the constant term of the line that fits best the data in the sense of the least squares method. Write a function, that returns π‘Ž,𝑏,𝑦, where π‘Ž is the slope, 𝑏 is the constant term of the needed line and 𝑦=π‘Žπ‘₯+𝑏. Additional information: 3β‰€π‘šβ‰€10 In each of the cases the solution is uniquely determined by the data. For this problem it is forbidden to use the functions polyfit, linsolve,\

function [a,b,y]=solve(t,f,x)
A = [t, ones(length(t), 1)];
m = mldivide((A' * A), (A' * f));
a = m(1);
b = m(2);
y = a*x' + b;
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for a function 𝐹(𝑑)=π‘Ž/𝑑 + 𝑏 that fits best the data in the sense of least squares method. Write a function, that returns π‘π‘Žπ‘Ÿπ‘ =(π‘Ž,𝑏) and 𝑦=(𝐹(π‘₯1),...,𝐹(π‘₯n)) for parameters 𝑑,𝑓,π‘₯. Additional information: 3β‰€π‘šβ‰€10 2≀𝑛≀5 In each of the cases the solution is uniquely determined by the data.

function [pars,y]=solve(t,f,x)
A = [1./t ones(length(t), 1)];
m = ((A' * A) \ (A' * f));
a = m(1);
b = m(2);
y = a./x' + b;
pars = [a, b];
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for the parameters π‘Ž,𝑏,𝑐 of the function 𝐹(𝑑)=π‘Žπ‘‘ + 𝑏(𝑒^(1/𝑑)) + 𝑐(𝑑/(1+𝑑)) that fits best the data in the sense of least squares method and the values of 𝐹 at the given locations π‘₯=(π‘₯1,...,π‘₯n). Write a function, that returns the vectors π‘π‘Žπ‘Ÿπ‘ =(π‘Ž,𝑏,𝑐) and 𝑦=(𝐹(π‘₯1),...,𝐹(π‘₯n)) for the given data 𝑑,𝑓,π‘₯. Additional information: 3β‰€π‘šβ‰€10 1≀𝑛≀5 For each case the parameters of the model are uniquely determined by the data.

function [pars,y]=solveit(t,f,x)
A = [t exp(1./t) t./(1+t)];
m = (A'*A) \ (A'*f);
a = m(1);
b = m(2);
c = m(3);
y = a*x' + b.*exp(1./x') + c*(x'./(1+x'));
pars = [a,b,c];
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for the parameters π‘Ž,𝑏,𝑐 of the function 𝐹(𝑑)=π‘Ž + 𝑏𝑑 + 𝑐(𝑑^2) that fits best the data in the sense of least squares method and the values of 𝐹 at the given locations π‘₯=(π‘₯1,...,π‘₯n). Write a function, that returns the vectors 𝑦=(𝐹(π‘₯1),...,𝐹(π‘₯𝑛)) for the given data 𝑑,𝑓,π‘₯. Additional information: 3β‰€π‘šβ‰€10 1≀𝑛≀5 For each case the parameters of the model are uniquely determined by the data.

function y=solve(t,f,x)
A = [ones(length(t),1) t t.^2];
m = (A'*A) \ (A'*f);
a = m(1);
b = m(2);
c = m(3);
y = a + b*x' + c*x'.^2;
pars = [a,b,c];
end

For the given locations 𝑑=(𝑑1,...𝑑m) and values 𝑓=(𝑓1,...,𝑓m), we are searching for the parameters π‘Ž,𝑏,𝑐 of the function 𝐹(𝑑)=π‘Žcos(πœ‹π‘‘)+𝑏sin(πœ‹π‘‘)+𝑐 that fits best the data in the sense of least squares method and the values of 𝐹 at the given locations π‘₯=(π‘₯1,...,π‘₯n). Additional information: 3β‰€π‘šβ‰€10 1≀𝑛≀5 For each case the parameters of the model are uniquely determined by the data.

function y=solve(t,f,x)
A = [cos(pi.*t) sin(pi.*t) ones(length(t),1)];
m = (A'*A) \ (A'*f);
a = m(1);
b = m(2);
c = m(3);
y = a.*cos(pi.*x') + b.*sin(pi.*x') + c;
end

lagpoly 1:

Interpolate the points (2,3) and (1,5) by a minimal degree polynomial. What is the value of the resulting polynomial at βˆ’10?

t = [2 1];
f = [3 5];
p = polyfit(t, f, 1);
polyval(p, -10)

Interpolate the points (βˆ’9,56/3), (βˆ’2,0) and (3,20/3) by a minimal degree polynomial. What is the main coefficient of the resulting polynomial?

t = [-9 -2 3];
f = [56/3 0 20/3];
format rat
p = polyfit(t, f, 2)

Interpolate the points (βˆ’9,βˆ’2373), (βˆ’6,βˆ’735), (βˆ’2,βˆ’35) and (βˆ’3,βˆ’105) by a minimal degree polynomial. What is the main coefficient of the resulting polynomial?

t = [-9 -6 -2 -3];
f = [-2373 -735 -35 -105];
format rat
p = polyfit(t, f, 3)

Interpolate the points (βˆ’3,14), (βˆ’1,2) and (βˆ’9,98) by a minimal degree polynomial. What is the value of the resulting function at 10?

t = [-3 -1 -9];
f = [14 2 98];
p = polyfit(t, f, 2);
polyval(p, 10)

What is the degree of the polynomial that interpolates the data below?

image

t = [2 -4 -5 -6];
f = [11 29 46 67];
plot(t, f)

lagpoly 2:

Using Horners tabular method, we compute 𝑃(βˆ’2) for the polynomial 𝑃(π‘₯) = 4(π‘₯^5) – 4(π‘₯^4) + 3(π‘₯^2) βˆ’ 2π‘₯ – 4 Then, the value under the degree 1 term is:

https://elsenaju.eu/Calculator/Horners-method.htm

image

Using Horner’s tabular method, we compute 𝑃(βˆ’3) for the polynomial 𝑃(π‘₯)=βˆ’3(π‘₯^4) + 4π‘₯ – 4

image

Compute the missing values. X= Y=

https://elsenaju.eu/Calculator/Horners-method.htm

image

Lagpoly 3():

image

We are going to interpolate the data 𝑑,𝑓 with a minimal degree polynomial. Compute the missing entries of the table below!

image

X = (703-118)/(-3-2)
Y = (138-703)/(-2+3)
Z = (X-57)/(-3-0)
U = (-131-Y)/(-1+3)
V = (U-112)/(-1-2)
W = (V+27)/(-1-0)

% The value of the needed polynomial at 3:
t = [0, 2, -3, -2, -1];
f = [4, 118, 703, 138, 7]; 
p = polyfit(t, f, 4);
polyval(p, 3)

or

% Note this code tested once only
t = [0, 2, -3, -2, -1];
f = [4, 118, 703, 138, 7];
value_at=3;
% DO NOT CHANGE ANYTHING BELOW THIS %
% Number of data points
n = numel(t);
% Initialize the Lagrange interpolation table
Lagrange_table = zeros(n, n+1);
% Compute the Lagrange coefficients
for i = 1:n
Lagrange_table(i, 1) = t(i);
Lagrange_table(i, 2) = f(i);
end
% Compute the missing values in the table
for j = 3:n+1
for i = 1:n-j+2
Lagrange_table(i, j) = (Lagrange_table(i+1, j-1) - Lagrange_table(i, j-1)) / (t(i+j-2) - t(i));
end
end
% Display the Lagrange interpolation table
Lagrange_table
value_at_answer = polyval(polyfit(t,f,(n-1)),value_at)

numint 1:

image

What is the value of the above integral? Use the function integral!

f1 = @(x) cos(x + pi) .* sin(2 .* (x.^2) - pi);
integral(f1, -25, -9)

image

What is the value of the above integral? Use the function integral!

f1 = @(x) cos(x) .* 1./(2 + (x.^2));
integral(f1, 2.0, inf)

image

What is the value of the above integral? Use the function integral2!

f1 = @(x, y) cos(x + pi) .* exp((-x.^2) - (y.^2));
result = integral2(f1, -1, 3, -3, 4)

image

What is the value of the above integral? Use the function integral2!

f1= @(x,y) 1./((x.^4) +1).* exp(-0.8*(x.^2) -0.2* (y.^2)); 
f2 = @(x) 2*x;
integral2(f1, 0, 3, -1, f2)

numint 2:

The approximate value of the definite integral

image

computed by the simple trapesoidal and midpoint rules are :

f = @(x) x.*exp(1./x);
a = 1;
b = 4;
%DO NOT MODIFY ANYTHING BELOW
trapezoidal_approximation = (b-a) * (f(a) + f(b)) / 2;
simple_simpson_approximation = (b-a) * (f(a) + 4*f((a+b)/2) + f(b)) / 6; 
midpoint_approximation= (b-a) * f((a+b)/2);
% Display the results
trapezoidal_approximation
simple_simpson_approximation
midpoint_approximation

Approximating the integral

image

using the compound midpoint and trapesoidal rules, dividing the interval into 4 parts, the results are:

f = @(x) x.*sin(2*(x.^2) - pi);
a = 2;
b = 4;
n = 4;
%DO NOT MODIFY ANYTHING BELOW
h = (b - a) / n;
compound_trapezoidal_approximation = 0; 
compound_simple_simpson_approximation = 0; 
compound_midpoint_approximation = 0;
for i = 1:n
    x0 = a + (i-1) * h;
    x1 = a + i * h;
    compound_trapezoidal_approximation = compound_trapezoidal_approximation + (x1 - x0) * (f(x0) + f(x1)) / 2;
    x_mid = (x0 + x1) / 2;
    compound_simple_simpson_approximation = compound_simple_simpson_approximation + (x1 - x0) * (f(x0) + 4*f(x_mid) + f(x1)) / 6;
    compound_midpoint_approximation = compound_midpoint_approximation + (x1 - x0) * f(x_mid); 
end
% Display the compound approximations
compound_trapezoidal_approximation 
compound_simple_simpson_approximation 
compound_midpoint_approximation

nunlin 1():

In order to approximate a root of the function

image

we apply Newton method with the starting pont π‘₯0 = 19/4 and perform 3 iterations. Then π‘₯3 =

f = @(x) (-9/4)*(x.^2) + (45/8)*x + (-189/64); 
x0 = 19/4;
n = 3;
%Do not modify below
h = 1e-6;
df = @(x) (f(x + h) - f(x - h)) / (2 * h);
x = x0;
for i = 1:n
    x = x - f(x) / df(x); 
end
% Display the approximate root 
approx_root = x

Approximate the root of the function 𝑓(π‘₯) = π‘₯^2 βˆ’ 5 with Newton-method, starting from π‘₯0=1. Then π‘₯3=:

f = @(x) x.^2 -5;
x0 = 1;
n = 3;
%Do not modify below
h = 1e-6;
df = @(x) (f(x + h) - f(x - h)) / (2 * h);
x = x0;
for i = 1:n
    x = x - f(x) / df(x); 
end
% Display the approximate root 
approx_root = x

In order to approximate a root of the function

image

we apply Newton method with the starting pont π‘₯0 = 2 and perform 6 iterations. Then π‘₯6 =:

f = @(x) 2*(x.^2) - (19/4)*x + (3/2); 
x0 = 2;
n = 6;
%Do not modify below
h = 1e-6;
df = @(x) (f(x + h) - f(x - h)) / (2 * h);
x = x0;
for i = 1:n
    x = x - f(x) / df(x); 
end
% Display the approximate root 
approx_root = x

Approximate the root of the function

image

using the Newton method with initial point π‘₯0=βˆ’9. Choose the correct value of π‘₯2 from below:

The value of π‘₯17 is:

f = @(x) (1/28)*(x.^2) + (15/28)*x + (9/4); 
x0 = -9;
n = 2;
%Do not modify below
h = 1e-6;
df = @(x) (f(x + h) - f(x - h)) / (2 * h);
x = x0;
for i = 1:n
    x = x - f(x) / df(x); 
end
% Display the approximate root 
approx_root = x
%-----------------------------------------------------------
f = @(x) (1/28)*(x.^2) + (15/28)*x + (9/4); 
x0 = -9;
n = 17;
%Do not modify below
h = 1e-6;
df = @(x) (f(x + h) - f(x - h)) / (2 * h);
x = x0;
for i = 1:n
    x = x - f(x) / df(x); 
end
% Display the approximate root 
approx_root = x

eig 1():

The dominant eigenvalue of

image

% Define the matrix A
A=[-1 -5 -5; -3 10 8; 1 -1 -7]; 
% eig(A)
% Compute the eigenvalues and eigenvectors
[V, D] = eig(A);
eigenvalues = diag(D);
% Find the dominant eigenvalue and its corresponding eigenvector
[~, index] = max(abs(eigenvalues));
dominant_eigenvalue = eigenvalues(index);
dominant_eigenvector = V(:, index);
% Normalize the dominant eigenvector
dominant_eigenvector = dominant_eigenvector / norm(dominant_eigenvector);
% Display the dominant eigenvalue and eigenvector
dominant_eigenvalue
dominant_eigenvector

Consider the matrix

image

Choose the true statements about its eigenvalues and eigenvectors.

%% Determine the eigenvalues
A = [-1/2 -3; 15/4 -19/2];

% Calculate the eigenvalues
eigenvalues = eig(A);
sum(eig(A));
% Display the eigenvalues
disp('Eigenvalues:');
disp(eigenvalues);
disp('sum: ')
disp(sum(eig(A)))

%% how many eigenvalues it has
% Define the matrix A and eigenvalue lambda
A = [-1/2 -3; 15/4 -19/2];  % Modify the matrix as needed
lambda = -2;                % Select one of the actual eigen values

% Calculate the eigenvectors and eigenvalues
[V, D] = eig(A);
% Find the indices of eigenvalues matching lambda
lambda_indices = find(abs(diag(D) - lambda) < eps);
% Check if the specified eigenvalue exists
if isempty(lambda_indices)
    disp('The specified eigenvalue does not exist.');
else
    % Check the dimension of the eigenspace
    eigenspace_dimension = sum(abs(V(:, lambda_indices(1))) > eps);

    % Determine if there are infinitely many eigenvectors
    if eigenspace_dimension == 1
        disp('There is only one linearly independent eigenvector.');
    else
        disp('There are infinitely many eigenvectors.');
    end
end

For the matrix

image

and vector 𝑣T = [0 βˆ’1 1 βˆ’3] find the πœ† for which ||π΄π‘£βˆ’πœ†π‘£||2 is as small as possible.

A = [2 2 1 -2; 0 -3 -2 2; 1 3 -2 -1;-1 3 2 3];
v = [0,-1,1,-3]';
lambda = dot(A*v,v)/dot(v,v) 
% above is enough,second one double check different method.not sure how
% accurate
func = @(lambda2) norm(A*v - lambda2*v)^2; 
 % Minimize the objective function within the given range
lambda2 = fminbnd(func, -100, 100); 
lambda2

eig 2():

Find an eigenvector 𝑣 for the dominant eigenvalue of

image

% Define the matrix A
A=[14 0 -11 1; 0 7 7 -2; -11 7 21 -6; 1 -2 -6 3]; 
% Calculate the eigenvectors and eigenvalues
[V, D] = eig(A);
eigenvalues = diag(D);
% Find the dominant eigenvalue and its corresponding eigenvector
[~, index] = max(abs(eigenvalues));
dominant_eigenvalue = eigenvalues(index);
eigenvector_for_dominant_eigenvalue = V(:, index);
% Display the eigenvectors
disp('Eigenvectors:');
disp(eigenvector_for_dominant_eigenvalue);

Find an eigenvector 𝑣 for the dominant eigenvalue of

image

% Define the matrix A
A=[11 2 6; 2 14 -3; 6 -3 6]; 
% Calculate the eigenvectors and eigenvalues
[V, D] = eig(A);
eigenvalues = diag(D);
% Find the dominant eigenvalue and its corresponding eigenvector
[~, index] = max(abs(eigenvalues));
dominant_eigenvalue = eigenvalues(index);
eigenvector_for_dominant_eigenvalue = V(:, index);
% Display the eigenvectors
disp('Eigenvectors:');
disp(eigenvector_for_dominant_eigenvalue);

For the given 𝐴 and 𝑣0, compute 𝑣4 with power iteration.

image

𝑣0 = [3 3 2 βˆ’1]^T
Here, by power iteration we mean the following simple procedure: 𝑣0 is the initial vector

image

% Define the matrix A and vector v0 
A=[-1 2 0 3; -1 1 -1 3; 2 3 3 0; -2 1 -1 0]; %ReplacewithyourownmatrixA 
v0 = [3, 3, 2, -1]'; % Replace with your own vector v0
% Set the number of iterations ex: v4 means n=4
n = 4; % Specify the desired number of iterations 
% DO NOT MODIFY BELOW
% Perform power iteration
v = v0;
for i = 1:n
    v = A * v;
v = v / norm(v); % Normalize the vector at each iteration 
end
% Display the result 
v

In a rabbit population (considering only females) we have 3 age categories. We know the survival rates 𝑠 = (0.55,0.16,0.0) and the average reproduction rates: π‘Ÿ = (0.0,1.0,2.0). What is the stable distributoin for this population?

% Define the survival rates and average reproduction rates 
s = [0.55, 0.16, 0.0];
r = [0.0, 1.0, 2.0];
% Construct the Leslie matrix 
L = [r(1), r(2), r(3);
    s(1), 0, 0;
    0, s(2), 0];
% Do not modify code below
% Calculate the dominant eigenvalue and eigenvector 
[V, D] = eig(L);
eigenvalues = diag(D);
[~, index] = max(abs(eigenvalues)); 
dominant_eigenvalue = eigenvalues(index); 
stable_distribution = V(:, index);
% Normalize the stable distribution to sum to 1
stable_distribution = stable_distribution / sum(stable_distribution);
% Display the stable distribution 
stable_distribution

optim 1:

Among the locations at which the function

image

has a local maximum, the smallest in absolute value is:

f = @(x) -sin(1/64*x^3) - cos(3/4*x);
% Search for the minimum of -f(x) in the interval [0, 4] 
[x_min, ~] = fminbnd(@(x) -f(x), 0, 4); 
location = x_min

Among the roots of the function

image

the smallest in absolute value is:

% Define the function
f = @(x) -sin((1/512)*(x.^3)) - cos((3/8)*x);

% Set the desired tolerance
tolerance = 1e-6;

% Set the search interval
a = -10; % Lower bound
b = 10;  % Upper bound

% Initialize variables
smallestRoot = inf;
root = 0;

% Perform bisection method
while (b - a) > tolerance
    % Calculate midpoint
    c = (a + b) / 2;

    % Evaluate the function at midpoint
    f_c = f(c);

    % Check if f(c) is a root
    if abs(f_c) < smallestRoot
        smallestRoot = abs(f_c);
        root = c;
    end

    % Update the interval
    if sign(f_c) == sign(f(a))
        a = c;
    else
        b = c;
    end
end

% Display the smallest root
fprintf('The smallest root in absolute value is: %.6f\n', root);

Among the locations at which the function

image

has a local minimum, the smallest in absolute value is:

% Define the objective function
f = @(x) cos(49*x^2) - sin(14*x);

% Define the objective function for fminsearch
objective = @(x) f(x);

% Set initial guess for the minimum location
x0 = 0;

% Perform the optimization
options = optimset('Display', 'off');
minimum_location = fminsearch(objective, x0, options);

% Display the result with higher precision
fprintf('The approximate location of the local minimum is x = %.4f\n', minimum_location);

Among the points in [-40/33, 40/33] x [-40/33, 40/33] at which the function f(x, y) = ((1089/64)*x^2 - (33/8)*y - 11)^2 + ((-33/8)*x + (1089/64)*y^2 - 7)^2 has a local minimum, the smallest in absolute value is:

% Define the function
f = @(x) ((1089/64)*x(1)^2 - (33/8)*x(2) - 11)^2 + ((-33/8)*x(1) + (1089/64)*x(2)^2 - 7)^2;

% Define the lower and upper bounds for the variables
lb = [-40/33, -40/33];
ub = [40/33, 40/33];

% Define the constraint function (empty in this case)
nonlcon = [];

% Define the initial guess for optimization
x0 = [0, 0];

% Set the options for optimization
options = optimoptions('fmincon', 'Display', 'off');

% Perform the constrained optimization
x_min = fmincon(f, x0, [], [], [], [], lb, ub, nonlcon, options);

x_min

Among the points in [βˆ’1, 1]Γ—[βˆ’1, 1] at which the function

image

has a local minimum, the closest to the origin is:

% Define the function
f = @(x) ((25)*x(1)^2 - (5)*x(2) - 11)^2 + ((5)*x(1) + (25)*x(2)^2 - 7)^2;

% Define the lower and upper bounds for the variables
lb = [-1, -1];
ub = [1, 1];

% Define the constraint function (empty in this case)
nonlcon = [];

% Define the initial guess for optimization
x0 = [0, 0];

% Set the options for optimization
options = optimoptions('fmincon', 'Display', 'off');

% Perform the constrained optimization
x_min = fmincon(f, x0, [], [], [], [], lb, ub, nonlcon, options);

x_min

linprog 1:

A calculator company produces a plain scientific calculator and a graphing calculator. Long-term projections indicate an expected demand of at least 108 scientific and 72 graphing calculators each day. Because of limitations on production capacity, no more than 192 scientific and 161 graphing calculators can be made daily. To satisfy a shipping contract, a total of at least 301 calculators much be shipped each day. If each scientific calculator sold results in a 2 unit gold loss, but each graphing calculator produces a 3 unit gold profit, how many of each type should be made daily to maximize the net profit? What is the maximal net profit? The optimal quantity for plain calculators: The optimal quantity for graphing calculators: The maximal net profit is:

% Define the constraint matrix Aeq and RHS vector beq 
% x + y = 301
Aeq = [1 1];
beq = [301];
% Define the coefficient vector c 
c = [-2; 3];
% Define the lower bounds lb and upper bounds ub 
lb = [108; 72];
ub = [192; 161];
% Solve the linear programming problem
[x, fval] = linprog(-c, [], [], Aeq, beq, lb, ub);
maximum_quantity_for_plain_calculators = x(1) 
maximum_quantity_for_graphing_calculators = x(2) 
maximum_profit= -fval

Error:

%How large can be relative error of the solution in #-norm 
A=[];
given_number=;
c = cond(A, #); 
c*given_number
%How large can be the relative error on the right hand side in # norm 
A=[];
given_number=;
c = cond(A,#);
given_number/c

Choose the false statements about the given vector and matrix.

% Define the matrix A and vector b
A = [3/2 3/2 3/2;-4 2 -1/2;-2 -2 -2]; % Define your matrix A here
b = [1 5 -3]'; % Define your vector b here
%for invertible,linear dependent. 1= true,0 false
%for Ax=b solutions -1 means inf'
%Do not modify below
num_unknowns= size(A,2);
% Calculate the determinant of A
det_A = det(A);
% Calculate the rank of A
rank_A = rank(A);
% Check if A is invertible
is_invertible = (det_A ~= 0);
% Solve the linear system Ax = 0
null_space = null(A);
num_null_space_columns = num_unknowns - rank_A;  % Number of columns in the null space
num_solutions_0 = 2^num_null_space_columns;  % Number of solutions for Ax = 0
% Check if the columns of A form a linearly independent system
is_linearly_independent = (num_null_space_columns == 0);
% Augment A with b to form the augmented matrix [A, b]
augmented_matrix = [A, b];
% Calculate the rank of the augmented matrix [A, b]
rank_augmented = rank(augmented_matrix);
% Determine the number of solutions for Ax = b
if rank_A == rank_augmented
    if rank_A == num_unknowns
        num_solutions = 1;
    else
        num_solutions = -1;
    end
else
    num_solutions = 0;
end
% Calculate the first element of transpose(A) * b
first_element = A' * b;
first_dc = b'*A';
% Display the results
disp(['Determinant of A: ' num2str(det_A)]);
disp(['Rank of A: ' num2str(rank_A)]);
disp(['Is A invertible? ' num2str(is_invertible)]);
disp(['Number of solutions for Ax = 0: ' num2str(num_solutions_0)]);
disp(['Columns of A form a linearly independent system? ' num2str(is_linearly_independent)]);
disp(['Number of solutions for Ax = b: ' num2str(num_solutions)]);
disp(['First element of transpose(A) * b: ' num2str(first_element(1)) ]);
disp(['First element of transpose(b) * transpose(A): ' num2str(first_dc(1)) ]);

Consider the function f(x) = e^x - x^2

image

We are searching for a root of f with the Newton method, starting from x0, performing k iterations. Write a function, that returns xk and fk=f(xk).

function [xk,fk]=solveit(x0,k)
  f=@(x) exp(x)-x.^2;
  df=@(x) exp(x)-2*x;
  xk=x0;
  for it=1:k
    xk=xk-f(xk)/df(xk);
  end
  fk=f(xk);
end

Given the function f(x) = |x| / (1+(e^(-x)). Evaluate it at the locations t=(t1,...,tn). Interpolate the obtained data by a minimal degree p polynomial, then evaluate p at x. Write a function, that returns px=p(x) and pd for a given t,x,d, where pd is the d-th order terms coefficient of p. The figure below is tightly related to the task, but your solution does not need to plot!

image

function [px,pd]=solveit(t,x,d)
  fun=@(x) abs(x)/(1+exp(-x));
  n=length(t);
  pol=polyfit(t,arrayfun(fun,t),n-1);
  px=polyval(pol,x);
  pd=pol(end-d);
end

Approximate the solution of f(x)=0 with the bisection method. Write a function, that implements the algorithm below.

image

Additional information:

You may assume, that f is continuous on [a,b]. Your solution should compute exactly maxit new intervals.

function [a, b] = solveit(f, a, b, maxit)
    if a < b && f(a) * f(b) < 0
        i = 0;
        while true
            i = i + 1;
            if i > maxit
                break;
            end
            mid = (a + b) / 2;
            if f(a) * f(mid) < 0
                b = mid;
            else
                a = mid;
            end
        end
    end
end

Did you find this article valuable?

Support Mojtaba Maleki by becoming a sponsor. Any amount is appreciated!

Β