我想将以下matlab代码实现为R(变量中有一些变化(,但它不起作用。有人(一个好的翻译!!(能帮我吗?
这是matlab代码:
% Define domain
dx = 0.001;
L = pi;
x = (-1+dx:dx:1)*L;
n = length(x); nquart = floor(n/4);
% Define hat function
f = 0*x;
f(nquart:2*nquart) = 4*(1:nquart+1)/n; f(2*nquart+1:3*nquart) = 1-4*(0:nquart-1)/n;
plot(x,f,’-k’,’LineWidth’,1.5), hold on
% Compute Fourier series
CC = jet(20);
A0 = sum(f.*ones(size(x)))*dx;
fFS = A0/2; for k=1:20
A(k) = sum(f.*cos(pi*k*x/L))*dx; % Inner product B(k) = sum(f.*sin(pi*k*x/L))*dx;
fFS = fFS + A(k)*cos(k*pi*x/L) + B(k)*sin(k*pi*x/L);
plot(x,fFS,’-’,’Color’,CC(k,:),’LineWidth’,1.2) end
以及我在R:方面的努力
dx = 0.01
L = 2
x = seq(-L,L,dx)
n = length(x)
y = floor(n/4)
f = rep(0,n)
a = 0
b = y;b
c = y*2;c
d = y*3;d
e = n;e
f[a:b] = 0
f[b:c] = 1
f[c:d] =-1
f[d:e] = 0
A0 = sum(rep(f,n)) *dx ;A0
fFS = A0/2
m = 100
Am = numeric(0)
Bm = numeric(0)
for (i in 0:m){
Am[i] = sum(f * cos(pi*(i)*x/L) ) * dx
Bm[i] = sum(f * sin(pi*(i)*x/L) ) * dx
Fou = fFS + Am[i] *cos((i)*pi*x/L) + Bm[i] *sin((i)*pi*x/L)
}
plot(x,f,type="l",col="blue")
lines(x,Fou,type="l",col="orange")
为什么我的代码不起作用?
感谢Unlander Monica的激励和力量。如果你去希腊雅典,我会给你一杯咖啡
dx = 0.01
L = 2*pi
x = seq(0,L+dx,dx)
n = length(x);n
y = floor(n/4);y
f = rep(0,length(x));f
a = 0
b = y;b
c = y*2;c
d = y*3;d
e = n;e
f[a:b] = 0
f[b:c] = 1
f[c:d] = 1
f[d:e] = 0
f
A0 = sum(f * rep(1,n)) *dx*2/ L
fFS = (A0/2) * rep(1,length(f))
n = 100
for(i in 1:n){
Am = sum(f * cos((2*pi*(i)*x)/L)) * dx*2 / L
Bm = sum(f * sin((2*pi*(i)*x)/L)) * dx*2 / L
fFS = fFS + Am*cos((2*(i)*pi*x)/L) + Bm*sin((2*(i)*pi*x)/L)
}
plot(x,f,type="l","col"="blue")
lines(x,fFS,type="l","col"="darkorange")