Clear Filters
Clear Filters

Plotting in a Loop

2 views (last 30 days)
Asli Merdan
Asli Merdan on 25 Mar 2018
Commented: Walter Roberson on 3 Apr 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 ?

Accepted Answer

Walter Roberson
Walter Roberson on 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 Comments
Asli Merdan
Asli Merdan on 3 Apr 2018
Edited: Asli Merdan on 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 on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!