Why is my if counter not working
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (3)
VBBV
il 22 Apr 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 Commenti
Bruno Luong
il 22 Apr 2022
Modificato: Bruno Luong
il 22 Apr 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 Commenti
Manash Sahoo
il 22 Apr 2022
Modificato: Manash Sahoo
il 22 Apr 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 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!