Azzera filtri
Azzera filtri

Plotting in a Loop

2 visualizzazioni (ultimi 30 giorni)
Asli Merdan
Asli Merdan il 25 Mar 2018
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 ?

Risposta accettata

Walter Roberson
Walter Roberson il 25 Mar 2018
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 Commenti
Asli Merdan
Asli Merdan il 3 Apr 2018
Modificato: Asli Merdan il 3 Apr 2018
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 il 3 Apr 2018
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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by