While loop - display the last value while statement is still true

The example given on Mathworks doesn't make sense to me.
x=0
p=1-poisscdf(1,x);
while p<=0.1
x=x+0.01;
p=1-poisscdf(1,x);
end
display(x);
The x value given at the end of the loop is the first value that makes the statement false.What can I add to the script so that display(x) gives me the last value that makes the statement true?
*Edit:
I just tried:
x=0;
p=1-poisscdf(1,x);
while p2more<=0.1
x=x+0.01;
p=1-poisscdf(1,x);
if p>=0.1
break
end
display(x);
end
Now I get all the values of x where this statement is true. I just want the last value. :X

 採用された回答

James Tursa
James Tursa 2017 年 3 月 21 日
編集済み: James Tursa 2017 年 3 月 21 日

1 投票

You could just use another variable. E.g., y
x=0
p=1-poisscdf(1,x);
while p<=0.1
y = x; % <-- save current value of x
x=x+0.01;
p=1-poisscdf(1,x);
end
display(y); % <-- display last value of x for which test was true

3 件のコメント

astein
astein 2017 年 3 月 24 日
Thank you! I accepted this since it was posted earlier, but Jan Simon also provided this solution. Thumbs up to you both.
If it's not too much trouble could you explain why using another variable got me to the last value of x for which the test was true?
James Tursa
James Tursa 2017 年 3 月 24 日
Right after the test passes, you save the x value that made the test pass. But when you generate an x value that doesn't pass the test, you don't execute the y = x statement. So it is only the x values that pass the test that are saved in y. And the last one is what makes it to the display(y) statement.
astein
astein 2017 年 3 月 24 日
Thank you, that was really helpful.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2017 年 3 月 21 日
編集済み: Jan 2017 年 3 月 21 日

1 投票

The trivial soultion is:
x = 0;
p = 1 - poisscdf(1, x);
while p <= 0.1
x = x + 0.01;
p = 1 - poisscdf(1, x);
end
x = x - 0.01;
display(x);
If the increasing of x is not a constant:
x = 0;
lastx = x;
p = 1 - poisscdf(1, x);
while p <= 0.1
lastx = x;
x = x + 0.01;
p = 1 - poisscdf(1, x);
end
display(lastx);
Now p is defined twice and redundacies in the code are prone to bugs: If one instance is modified later, that other might be forgotton. To avoid this:
x = 0;
ready = false
while ~ready
p = 1 - poisscdf(1, x);
ready = (p < 0.1);
lastx = x;
x = x + 0.01;
end
display(lastx);

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2017 年 3 月 20 日

コメント済み:

2017 年 3 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by