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!