I have to make code for the following but don't know how to use put sigma into matlab
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have to make code for the following but don't know how to use put sigma into matlab
1 commentaire
C.J. Harris
le 20 Mar 2018
Maybe that's why your homework is suggesting you use a for-loop instead...
Réponses (1)
Abraham Boayue
le 21 Mar 2018
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
0 commentaires
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!