My code is giving me a straight line for values of N other than 5

1 Ansicht (letzte 30 Tage)
Kayla Howell
Kayla Howell am 1 Dez. 2022
Bearbeitet: Torsten am 2 Dez. 2022
clear variables
close all
M = 250; % The length of each function
t = -5:0.1:5;
y = zeros(1,M); % Initiallize the sum to zero
N = 2;
for k=N
ck = (cos(k*pi)-1);
b= (2/((k*pi)^2))*(cos(k*pi*t));
syms k
y= symsum(0.5+(ck*b),k,1,N); % computing the sum
end
plot(t,y,'linewidth',2,'color','m')
a= title('x(t)');
set(a,'fontsize',14);
a= xlabel('x');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid;

Antworten (3)

matt
matt am 1 Dez. 2022
Define k as symbolic before defining b and ck. In your posted code, when the for loop is entered, k=N=2 so ck = (cos(2*pi)-1)=0 and b=(2/((2*pi)^2))*(cos(2*pi*t)). when symsum is reached, syms k is not defined in the function 0.5+(ck*b).
best, matt
clear variables
close all
M = 250; % The length of each function
t = -5:0.1:5;
y = zeros(1,M); % Initiallize the sum to zero
N = 2;
for k=N
syms k
ck = (cos(k*pi)-1);
b= (2/((k*pi)^2))*(cos(k*pi*t));
y= symsum(0.5+(ck*b),k,1,N); % computing the sum
end
plot(t,y,'linewidth',2,'color','m')
a= title('x(t)');
set(a,'fontsize',14);
a= xlabel('x');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid;

Torsten
Torsten am 1 Dez. 2022
Bearbeitet: Torsten am 2 Dez. 2022
I'm quite sure that the 0.5 has to be taken out of the symsum:
syms k N integer
syms t
y = 0.5 + symsum((cos(k*pi)-1)*(2/((k*pi)^2))*(cos(k*pi*t)),k,1,N)
y = 
tnum = -5:0.01:5;
Nnum = 2;
ynum = arrayfun(@(tnum)double(subs(y,[N t],[Nnum tnum])),tnum);
plot(tnum,ynum)

VBBV
VBBV am 1 Dez. 2022
clear variables
close all
M = 250; % The length of each function
t = -5:0.1:5;
y = zeros(1,M); % Initiallize the sum to zero
N = 2;
syms k
for n=1:N
ck = (cos(k*pi)-1);
b= (2/((k*pi)^2))*(cos(k*pi*t));
y= symsum(0.5+(ck*b),k,1,n); % computing the sum
plot(t,y,'linewidth',2)
hold on
end
legend('N=1','N=2','location','best')
a= title('x(t)');
set(a,'fontsize',14);
a= xlabel('x');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
grid;

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by