% 강의 main-01-10.m의 다항식과 도함수를 브라우저에서도 그린다.
% 두 곡선을 다시 그린 뒤 drawnow로 표시한다. 영상 파일은 만들지 않는다.
clear;
close all;

function values = evaluate_polynomial (coefficients, time_s)
  % 호너법으로 각 시각에서 다항식 값을 계산한다.
  % 호출 형식: values = evaluate_polynomial(coefficients, time_s)
  % 입력 인자
  % coefficients
  % 자료형: 실수. 크기: 비어 있지 않은 행 벡터. 단위: 항에 따름.
  % 의미: 최고차항부터 상수항까지의 다항식 계수.
  % time_s
  % 자료형: 실수. 크기: 행 벡터. 단위: 초. 의미: 계산할 시각.
  % 반환값
  % values
  % 자료형: 실수. 크기: time_s와 같음. 단위: 다항식에 따름. 의미: 다항식 값.
  % 사전조건: 계수가 하나 이상 있어야 한다.
  % 계산 순서: 최고차항의 계수에 시각을 곱해 다음 계수를 더하는 연산을 반복한다.
  % 호출 예: evaluate_polynomial([2, 1], [0, 1])은 [1, 3]을 반환한다.
  % 오류: 빈 계수는 첫 원소에 접근할 때 인덱스 오류가 난다.
  values = coefficients(1) + zeros(size(time_s));
  for term = 2:length(coefficients)
    values = values .* time_s + coefficients(term);
  endfor
endfunction

% p(t) = (t - 1)(t - 2)(t - 3)의 계수와 해석 도함수의 계수.
polynomial_coefficients = conv(conv([1, -1], [1, -2]), [1, -3]);
derivative_coefficients = [3, 2, 1] .* polynomial_coefficients(1:3);

% 강의와 같은 [0.8, 3.2) 구간에서 일정 간격으로 10,000개를 계산한다.
time_span_s = [0.8, 3.2];
sample_count = 10000;
dt_s = (time_span_s(2) - time_span_s(1)) / sample_count;
time_s = time_span_s(1) + (0:sample_count-1) * dt_s;
polynomial = evaluate_polynomial(polynomial_coefficients, time_s);
derivative = evaluate_polynomial(derivative_coefficients, time_s);
forward_difference = (polynomial(2:end) - polynomial(1:end-1)) / dt_s;

% 원본은 매 20번째 인덱스까지의 모든 점을 다시 그린다. 여기서는
% 그 인덱스의 점 500개만 그려 원본과 같은 9981번째 샘플에서 끝낸다.
% 첫 점을 그린 뒤 최대 10점씩 늘려 500번 대신 51번 화면을 갱신한다.
draw_indices = 1:20:sample_count;
draw_points = length(draw_indices);
points_per_frame = 10;
frame_ends = [1, points_per_frame:points_per_frame:draw_points-1, draw_points];
frame_period_s = 0.04;

figure;
for last_point = frame_ends
  indices = draw_indices(1:last_point);
  plot(time_s(indices), polynomial(indices), 'b-', 'LineWidth', 1.2, ...
       time_s(indices), derivative(indices), 'r--', 'LineWidth', 1.2);
  grid on;
  xlabel('Time [s]');
  ylabel('Amplitude');
  title('Polynomial and its derivative');
  legend('p(t)', "p'(t)", 'Location', 'southeast');
  drawnow;
  pause(frame_period_s);
endfor

sample_count
last_calculated_time_s = time_s(end)
last_drawn_time_s = time_s(draw_indices(end))
max_forward_difference_error = max(abs(forward_difference - derivative(2:end)))
