Name: Anonymous 2011-04-09 0:33
What's your favorite thing about MATLAB / Simulink?
It's hard to choose but for me I'd probably have to go with the powerful matrix math and plot tools.
It's hard to choose but for me I'd probably have to go with the powerful matrix math and plot tools.
clear;clc;close all;
k = 5; %highest order fourier series
n = 2^13; %length of vectors
t_n = 2 * pi;
t = linspace(0, t_n, n);
w_0 = 2*pi/t_n; %angular frequency
%function definition
f = sin(t) .* (t < t_n/4);
f = f + 1 .* (t >= t_n/4);
f = f - (cos(t)+1) .* (t >= t_n/2);
f = f .* (t < 3*t_n/4);
t=t';f=f'; %transpose to create column vectors
a=ifft(f); %Fourier series coefficients
p=ones(n,k)*a(1)/2;
for i = 2 : k
for j = 2 : i
p(:,i)=p(:,i) + real(a(j))*cos((j-1)*w_0*t) ...
+ imag(a(j))*sin((j-1)*w_0*t);
end
end
p=2*p;
plot(t,f,'k'); hold on;
plot(t,p,'-.');
xlabel('t');ylabel('f');title('Fourier Series Approximations of f');
legend('f','1^s^t order approximation', ...
'2^n^d order approximation', ...
'3^n^d order approximation', ...
'4^t^h order approximation', ...
'5^t^h order approximation');
%%%%%%%%%%%
clear f;
n = 2 ^ 6;
x = linspace(-3, 3, n);
k = 3; %order of polynomial
%build polynomial
p=x;
for i = 2 : k
r = (x(n)-x(1)) * (rand()-.5);
p = p .* (x - r);
end
%build random function
for i = 1 : n
f(i) = p(i) + 15 * (rand() - .5);
end
q = polyval(polyfit(x,f,k),x); %curve fit random function
figure(2);
hold on;
plot(x,f,'.');plot(x,q,'k');plot(x,p,'m');
xlabel('x');ylabel('y');title('3^r^d order curve fit of random function');
legend('Random Data','Curve Fit of Random Data','Original Polynomial');
fprintf('Max difference between curve fit and original polynomial: %f\n', max(abs(p-q)));