- Look just above the text box, and you will find some useful tools for adding text formatting.
- Put two space characters at the beginning of each code line.
How can I fix my problem with (If loop) ?
1 view (last 30 days)
Show older comments
Hi everybody.
I have the following code to find the integral of (sin(x)) using monte-carlo simulation:
num = 10;100;1000;10000;1000000;
i10 = 0; i100 = 0 ; i1000 = 0; i10000 = 0; i1000000 = 0;
x = [0:(3.1416./100):3.1416];
y = [0:0.01:1];
for num = 10
figure (1);
hold on
axis([-0.2 3.6 -0.2 1.2]);
x = [0:(3.1416/100):3.1416];
y = [0:0.01:1];
xp = 0 + (3.1416 - 0).*rand (num,1);
yp = 0 + (1 - 0).*rand (num,1);
plot (x, sin(x))
rectangle ('position', [0,0,pi,1])
xlabel ('X'); ylabel ('sin (x)'); title ('sin (x) Vs. X');
legend ('a = 0, b = pi, No. of points: 10')
if (xp >= 0 & xp <= 3.1416) & (yp >= 0 & yp <= sin(xp))
i10 = i10 + 1
plot (xp, yp, '*')
else
plot (xp, yp, 'r+')
end
end
The problem id that when MATLAB run the program it produce a figure that ignore the (if loop) with the condition of: (xp >= 0 & xp <= 3.1416) & (yp >= 0 & yp <= sin(xp))
I am trying to fix this problem since four days but not able to do so. Please advise me, I am strongly upset.
The strange thing is that MATLAB does not show any error and it does perform the (for loop) and the (else) statement but ignoring the (if loop) statements.
Thanks a lot in advance
2 Comments
Stephen23
on 24 Sep 2014
Edited: Stephen23
on 24 Sep 2014
It really helps everyone if you edit your question and format your code properly. Two ways you can do this:
Make sure that you provide exactly the code that you are using, with indentation and everything :)
Answers (1)
Jan
on 27 Sep 2014
Edited: Jan
on 27 Sep 2014
What do you expect as result of this line:
num = 10;100;1000;10000;1000000;
It sets num to 10 and ignores the rest.
This is a loop over one value only, so it is not a loop in the usual ssense:
|for num = 10|
It is equivalent to:
num = 10;
After ths lines
xp = 0 + (3.1416 - 0).*rand (num,1);
yp = 0 + (1 - 0).*rand (num,1);
xp and yp are vectors. In the if condition:
if (xp >= 0 & xp <= 3.1416) & (yp >= 0 & yp <= sin(xp))
the argument is a vector also, such that Matlab performs applies an all() command internally. In consequence this condition is not true, when any element of yp is > sin(xp) .
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!