% Laboratory work 6
% Task 1


f = @(x) sin(exp(x));
g = @(x) 0.6*x.^2 - 0.5;
 
x_int1 = fzero(@(x) f(x) - g(x), 0)
x_int2 = fzero(@(x) f(x) - g(x), 1)
% for other initial point:
y_int1 = f(x_int1),y_int2 = f(x_int2)
 
figure;
fplot(f, 'b')
hold on
fplot(g, 'r')
grid on
%[xo,yo]=ginput(1)
%plot(xo,yo,'r.','markersize',40)
 
plot([x_int1;x_int2], [y_int1;y_int2], 'ko', 'MarkerSize', 10, 'MarkerFaceColor', 'g')
%gtext(sprintf('B(%.2f, %.2f)', x_int, y_int))
hold off

% Task 2 estimation

hold off
f = @(x) x.*sin(8*x)
g = @(x) x.^5 - x + 0.5
figure; % It is multiple root. Is it so?
fplot(f, [0.28, 0.31], 'b')
hold on;
fplot(g, [0.28, 0.31], 'r')
grid on;

% Task 2

f = @(x) x.*sin(8*x)
g = @(x) x.^5 - x + 0.5
difference = @(x) f(x) - g(x)

figure
hold on
fplot(f, [-1, 1], 'b', 'LineWidth', 1.5)
fplot(g, [-1, 1], 'r', 'LineWidth', 1.5)
grid on

initial_guesses = linspace(-1, 1, 10)
roots = arrayfun(@(x) fzero(difference, x), initial_guesses, 'UniformOutput', false)
roots = unique(round(cell2mat(roots), 6))

valid_roots = roots(abs(roots) <= 1)

y_coords = arrayfun(f, valid_roots)
plot(valid_roots, y_coords, 'ko', 'MarkerFaceColor', 'k')

title('Intersections of y=x\cdot sin(8x) and g=x^{5}-x+0.5')
xlabel('x')
ylabel('y')

arrayfun(@(i) text(valid_roots(i), y_coords(i), sprintf('(%0.2f, %0.2f)', valid_roots(i), y_coords(i)), ...
    'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'right'), 1:length(valid_roots));

hold off;

% Task 2 estimation

hold off
f = @(x) x.*sin(8*x)
g = @(x) x.^5 - x + 0.5
figure; % It is multiple root. Is it so? You see!
fplot(f, [0.28, 0.31], 'b')
hold on;
fplot(g, [0.28, 0.31], 'r')
x1x2=roots(2:3)'; f1f2=f(x1x2);
plot(x1x2,f1f2,'g.','markersize',40)
for i=1:2
    note=['(',num2str(x1x2(i),2),' ',num2str(f1f2(i),2),')']
text(x1x2(i),f1f2(i),note)
end
grid on;

% task3

f = @(x) x.*sin(x)
g = @(x) 1 - x.^2


x_int1 = fzero(@(x) f(x) - g(x), -1)
x_int2 = fzero(@(x) f(x) - g(x), 1)

y_int1 = f(x_int1)
y_int2 = f(x_int2)

figure;
fplot(f, [-2, 2], 'b')
hold on;
fplot(g, [-2, 2], 'r')
grid on;


plot([x_int1, x_int2], [y_int1, y_int2], 'ko', 'MarkerSize', 10, 'MarkerFaceColor', 'g');


legend('y = x sin(x)', 'y = 1 - x^2', 'Location', 'best')
title('Intersection of y = x sin(x) and y = 1 - x^2')
xlabel('x')
ylabel('y')


% task4

clear roots;

p = @(x) x.^5 + x.^2 - 10*x - 4.5;

roots_p = roots([1 0 0 1 -10 -4.5]);
poly_from_roots = poly(roots_p)

disp('Original polynomial coefficients:')
disp([1 0 0 1 -10 -4.5])
disp('Polynomial coefficients from roots:')
disp(poly_from_roots)
figure
fplot(p, [-3, 3], 'b')
hold on
grid on

scatter(real(roots_p), imag(p(roots_p)), 100, 'g', 'o', 'filled');

text(real(roots_p), imag(p(roots_p)), strtrim(cellstr(num2str(real(roots_p), '%.2f'))), ...
    'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'right');

real_roots_mask = abs(imag(roots_p)) < eps;
real_roots = roots_p(real_roots_mask);


if ~isempty(real_roots)
    scatter(real(real_roots), imag(p(real_roots)), 120, 'r', 's', 'filled');
end

xlabel('x');
ylabel('p(x)');
legend('p(x)', 'Roots', 'Real Roots');
hold off;

% task5

clear roots;
p = @(x) x.^5 + x.^2 - 10*x - 4.5
roots_p = roots([1 0 0 1 -10 -4.5])

coefficients = poly(roots_p)
disp('Original polynomial coefficients:')
disp([1 0 0 1 -10 -4.5])
disp('Polynomial coefficients from roots:')
disp(coefficients)

figure
fplot(p, [-3, 3], 'b')
hold on
grid on

real_roots = roots_p(imag(roots_p) == 0);
plot(real_roots, zeros(size(real_roots)), 'ro', 'MarkerSize', 10, 'MarkerFaceColor', 'r');

text(real_roots, zeros(size(real_roots)), arrayfun(@(x) sprintf('%.2f', x), real_roots, 'UniformOutput', false), ...
    'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'center')

title('Polynomial p(x) = x^5 + x^2 - 10x - 4.5 and its roots')
xlabel('x')
ylabel('p(x)')
legend('p(x)', 'Roots')
hold off

% task6

syms x
p_sym = x^5 + x^2 - 10*x - 4.5
p = matlabFunction(p_sym)
dp = matlabFunction(diff(p_sym))
d2p = matlabFunction(diff(diff(p_sym)))
sine_func = @(x) sin(x)

x_vals = linspace(-2, 2, 1000);

y = p(x_vals);
dydx = dp(x_vals);
d2ydx2 = d2p(x_vals);
y_sine = sine_func(x_vals);

dydx_num = gradient(y, mean(diff(x_vals)));
d2ydx2_num = gradient(dydx_num, mean(diff(x_vals)));


figure

plot(x_vals, y, 'b', 'DisplayName', 'p(x)')
hold on
plot(x_vals, dydx, 'r', 'DisplayName', 'p''(x) - sym')
plot(x_vals, d2ydx2, 'g', 'DisplayName', 'p''''(x) - sym')
plot(x_vals, dydx_num, 'm--', 'DisplayName', 'p''(x) - num')
plot(x_vals, d2ydx2_num, 'c--', 'DisplayName', 'p''''(x) - num')
plot(x_vals, y_sine, 'k:', 'DisplayName', 'sin(x)')

legend show
xlabel('x')
ylabel('y')
grid on
hold off

% task7

syms x
f = exp(sin(x^3))
df = diff(f, x)

f_num = matlabFunction(f)
df_num = matlabFunction(df)

xv = linspace(-2, 2.1, 1000);
fv = f_num(xv);
dfv = df_num(xv);

logical_vec=islocalmax(fv)
xmax=xv(logical_vec)'
ymax=fv(logical_vec)'

figure
plot(xv, fv, 'b', 'DisplayName', 'y = exp(sin(x^3))')
hold on
plot(xv, dfv, 'r', 'DisplayName', 'g(x) = y''(x)')

mp=plot(xmax,ymax,'g.','markersize',24,...
    'DisplayName','localMax' )

grid on


legend show
xlabel('x')
ylabel('y')
hold off

% task9

syms x
y = x*sin(8*x) - (x^5 - x + 0.5)

symbolic_integral = int(y, x, -0.6, 0.6)
symbolic_result = double(symbolic_integral)

numeric_integral = @(x) x.*sin(8*x) - (x.^5 - x + 0.5)
numeric_result = integral(numeric_integral, -0.6, 0.6)

disp(['Symbolic Integration Result: ', num2str(symbolic_result)])
disp(['Numerical Integration Result: ', num2str(numeric_result)])

if abs(symbolic_result - numeric_result) < 0.1e-4
    disp('The results match within the specified accuracy.');
else
    disp('The results do not match within the specified accuracy.');
end

% task10

syms x
f1 = exp(sin(x))
f2 = -x^2 + 8

figure
fplot(f1, [-4, 4], 'b', 'DisplayName', 'y = exp(sin(x))')
hold on;
fplot(f2, [-4, 4], 'r', 'DisplayName', 'y = -x^2 + 8')

x1 = double(vpasolve([f1-f2], x,-3))  % x0=-3 initial value
x2 = double(vpasolve([f1-f2], x,3))   % x0= 3 initial value
x=x1; y1=eval(char(f2))
x=x2; y2=eval(char(f2))
plot([x1;x2], [y1;y2], 'r.','markersize',24,'DisplayName','Intersections')

x = x1:0.01:x2; f2x = eval(char(vectorize(f2))); X1=x;
x = fliplr(x); f1x = eval(char(f1)); X2=x;
fl=fill([X1,X2],[f2x,f1x],'m')


xlabel('x')
ylabel('y')
grid on
hold off