필터 지우기
필터 지우기

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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by