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)

回答(3 个)

VBBV
VBBV 2022-4-22
s= 0
s = 0
x = linspace(-1,1, 50)
x = 1×50
-1.0000 -0.9592 -0.9184 -0.8776 -0.8367 -0.7959 -0.7551 -0.7143 -0.6735 -0.6327 -0.5918 -0.5510 -0.5102 -0.4694 -0.4286 -0.3878 -0.3469 -0.3061 -0.2653 -0.2245 -0.1837 -0.1429 -0.1020 -0.0612 -0.0204 0.0204 0.0612 0.1020 0.1429 0.1837
n = linspace(1,10,50)
n = 1×50
1.0000 1.1837 1.3673 1.5510 1.7347 1.9184 2.1020 2.2857 2.4694 2.6531 2.8367 3.0204 3.2041 3.3878 3.5714 3.7551 3.9388 4.1224 4.3061 4.4898 4.6735 4.8571 5.0408 5.2245 5.4082 5.5918 5.7755 5.9592 6.1429 6.3265
L = 2
L = 2
total = 0
total = 0
s= zeros(size(n))
s = 1×50
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
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
total = 26
plot(x,s)

Bruno Luong
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

Manash Sahoo
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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by