Borrar filtros
Borrar filtros

Plotting in a Loop

2 visualizaciones (últimos 30 días)
Asli Merdan
Asli Merdan el 25 de Mzo. de 2018
Comentada: Walter Roberson el 3 de Abr. de 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 ?

Respuesta aceptada

Walter Roberson
Walter Roberson el 25 de Mzo. de 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 comentarios
Asli Merdan
Asli Merdan el 3 de Abr. de 2018
Editada: Asli Merdan el 3 de Abr. de 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 el 3 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by