Why is my if counter not working
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
VBBV
2022-4-22
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 个评论
Bruno Luong
2022-4-22
编辑:Bruno Luong
2022-4-22
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 个评论
Manash Sahoo
2022-4-22
编辑:Manash Sahoo
2022-4-22
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!