フィルターのクリア

Plotting in a Loop

2 ビュー (過去 30 日間)
Asli Merdan
Asli Merdan 2018 年 3 月 25 日
コメント済み: Walter Roberson 2018 年 4 月 3 日
Sum=0;
for n=1:12341234
x=((-1)^(n-1))*(1/(2*n-1));
PiMe= Sum + 4*x;
RAbs=abs(PiMe-pi);
RER=RAbs/abs(pi);
while RER == 0.01
break
end
end
plot(n,RER(n))
I have a problem with plotting. I want to plot relative error for each n value. But I get a "Index exceeds matrix dimensions." problem. How can I solve it ?

採用された回答

Walter Roberson
Walter Roberson 2018 年 3 月 25 日
You do not assign to RER(n), and the value you do assign to RER is a scalar. At the end of the loop, RER(n) does not exist unless you were lucky enough to break on the first iteration.
Note: RER == 0.01 is unlikely to occur as you are calculating RER so it is going to have floating point round-off, and 0.01 is not exactly representable in binary floating point. You should be testing for inequality or you should be testing within tolerance.
There is no point using a while with something that will unconditionally break inside: you might as well using an if instead.
At the end of your loop, n will be the scalar that was last assigned to it by the for loop, so if you were to correct your code to plot(n,RER) to take into account that RER is a scalar, then you would be plotting only a single point, which is not going to show up.
Perhaps you want to record all the values of RER as you go along; in that case you could plot(RER) or plot(1:n,RER) or plot(1:n,RER(1:n)) . If you do record all of the values of RER as you go along, you should consider pre-allocating the output array.
  2 件のコメント
Asli Merdan
Asli Merdan 2018 年 4 月 3 日
編集済み: Asli Merdan 2018 年 4 月 3 日
I corrected the inequality but I still can not plot what I want. I need to assign every Relative Error to an array. How can I do it ?
Walter Roberson
Walter Roberson 2018 年 4 月 3 日
Sum = 0;
MaxIter = 12341234;
RER = zeros(1, MaxIter);
for n=1:MaxIter
x = ((-1)^(n-1))*(1/(2*n-1));
PiMe = Sum + 4*x;
RAbs = abs(PiMe-pi);
RER(n) = RAbs / abs(pi);
if RER(n) <= 0.01;
break;
end
end
plot(1:n,RER(1:n))
I find it odd that you would name a variable "Sum" but never add anything to it.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by