Why is my if counter not working
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Im trying to get my if counter to add each point when s is negative but it just produces 0 all the time
my counter here is total
s= 0
x = linspace(-1,1, 50)
n = 1:2:10
L = 2
total = 0
for i = 1:n
s = (8/(pi^2))*(s + (-1^(i-1/2)*(sin(i*pi*x/L)/i^2)))
if s(i) < 0
total = total + 1
end
end
plot(x,s)
0 comentarios
Respuestas (3)
VBBV
el 22 de Abr. de 2022
s= 0
x = linspace(-1,1, 50)
n = linspace(1,10,50)
L = 2
total = 0
s= zeros(size(n))
for i = 1:length(n)
s(i) = (8/(pi^2))*(s(i) + (-1^(i-1/2)*(sin(i*pi*x(i)/L)/i^2)));
if s(i) < 0
total = total + 1;
end
end
total
plot(x,s)
0 comentarios
Bruno Luong
el 22 de Abr. de 2022
Editada: Bruno Luong
el 22 de Abr. de 2022
Your for loop index is probably wrong, n should be scalar
n = 1:2:10
...
for i = 1:n
...
end
or perhaps you want this
n = 1:2:10
...
for i = n
...
end
0 comentarios
Manash Sahoo
el 22 de Abr. de 2022
Editada: Manash Sahoo
el 22 de Abr. de 2022
First off, your for loop.
Doing
n = 1:2:10
for i = 1:n
disp(i)
end
shows that your for loop will only run one time, so your if statement is only checked once.
If you want to loop through each element of n and use it in equation s you need to do this:
x = linspace(-1,1, 50)
n = 1:2:10
L = 2
figure;hold on;
for k = 1:numel(n)
i = n(k)
s = (8/(pi^2))*(s + (-1^(i-1/2)*(sin(i*pi*x/L)/i^2)))
end
If you want a total of how many numbers in s that are < 0, you can just do this:
total = numel(find(s < 0 == 1))
MS
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!