Approximation of e using random points
1 回表示 (過去 30 日間)
古いコメントを表示
I have plotted one random thousand points on an axis. I have also plotted a line y=1/x. Now I am trying to display the points below the line in blue and the points above the line in orange. I have tried using an if loop but have not been successful. Any ideas how I could do this? Thanks
採用された回答
Rick Rosson
2011 年 9 月 9 日
Hi Austin,
I have not tested the following code, so it may not be 100 percent correct, but it should give you the basic idea. I am assuming that you have two variables x and y, each one is a 1000 x 1 array of numbers:
idx = (y < 1./x);
figure;
scatter(x(idx),y(idx),'markerfacecolor','blue');
hold on;
scatter(x(~idx),y(~idx),'markerfacecolor','red');
HTH.
Rick
0 件のコメント
その他の回答 (7 件)
Rick Rosson
2011 年 9 月 9 日
Please try the following:
countBelow = sum(idx);
countTotal = size(x,1);
ratio = countBelow/countTotal;
HTH.
Rick
0 件のコメント
Rick Rosson
2011 年 9 月 9 日
Yes, you can solve it with either a for loop or a while loop in conjunction with an if statement. So you were on a perfectly valid path. But in MATLAB, it is almost always possible (and usually desirable) to eliminate for loops and while loops, and replace them with what is called vectorized code (which is what the idx = ... line is doing). Some of the benefits of vectorization include:
- Faster execution time
- More readable code
- More compact code
- More expressive code
- A higher level of abstraction
Also, in almost all programming languages, you generally want to avoid using if statements within loops if at all possible.
HTH.
Best,
Rick
0 件のコメント
Rick Rosson
2011 年 9 月 9 日
BTW, were you able to compute a good value for e using this method? How close to the correct value did you get?
0 件のコメント
Rick Rosson
2011 年 9 月 9 日
Please post a new question on MATLAB Answers with a link to this one for background info.
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!