I have to make code for the following but don't know how to use put sigma into matlab

조회 수: 3 (최근 30일)
I have to make code for the following but don't know how to use put sigma into matlab

답변 (1개)

Abraham Boayue
Abraham Boayue 2018년 3월 21일
This might help, try to understand how the for loop works, it is the basis of programming.
clear variables
close all
x = -5:0.1:5;
N = length(x);
y_sinx = zeros(1,N);
y1 = y_sinx;
y2 = y1;
y3 = y2;
M = [1 2 5 10];
% Although you were asked to use double for loops, but this is totally
% inefficient for such a simple problem.
for k = 1:N
sum = 0;
for n = 1:M(1)
sum = sum +((-1)^(n-1))*(x(k)^(2*n-1))/(factorial(2*n-1));
end
y_sinx(k) = sum;
end
for k = 1:N
sum = 0;
for n = 1:M(2)
sum = sum +((-1)^(n-1))*(x(k)^(2*n-1))/(factorial(2*n-1));
end
y1(k) = sum;
end
for k = 1:N
sum = 0;
for n = 1:M(3)
sum = sum +((-1)^(n-1))*(x(k)^(2*n-1))/(factorial(2*n-1));
end
y2(k) = sum;
end
for k = 1:N
sum = 0;
for n = 1:M(4)
sum = sum +((-1)^(n-1))*(x(k)^(2*n-1))/(factorial(2*n-1));
end
y3(k) = sum;
end
figure
subplot(221)
plot(x,y_sinx,'linewidth',2,'color','m')
legend('M = 1')
a= title('y(x) = sin(x)');
set(a,'fontsize',14);
a= xlabel('x [-5 5]');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid
subplot(222)
plot(x,y1,'linewidth',2,'color','g')
legend('M = 2')
a= title('y(x) = sin(x)');
set(a,'fontsize',14);
a= xlabel('x [-5 5]');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid
subplot(223)
plot(x,y2,'linewidth',2,'color','b')
legend('M = 5')
a= title('y(x) = sin(x)');
set(a,'fontsize',14);
a= xlabel('x [-5 5]');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid
subplot(224)
plot(x,y3,'linewidth',2,'color','r')
legend('M = 10')
a= title('y(x) = sin(x)');
set(a,'fontsize',14);
a= xlabel('x [-5 5]');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid
% A much better for loop. ( This is recommended)
% sum = zeros(1,N);
% for n = 1:M(3)
% sum = sum +((-1)^(n-1))*(x.^(2*n-1))/(factorial(2*n-1));
% end
% figure
% plot(x,sum,'linewidth',2,'color','r')
% a= title('y(t) : sum of sine wave');
% set(a,'fontsize',14);
% a= xlabel('x [-5 5]');
% set(a,'fontsize',20);
% a = ylabel('y');
% set(a,'fontsize',20);
% a = zlabel('z');
% set(a,'fontsize',20);
% grid

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by