Problem with loop for
2 views (last 30 days)
Show older comments
Hello
I need to calculate average value using various methods including loop for. I don't know why result using loop is diffrent. Can someone help with that?
N = 1200;
A = 2;
fx = 5;
fp = 1000;
dt = 1/fp;
t = dt*(0:N-1);
x = A*sin(2*pi*fx*t);
x_sred1 = mean(x); %average value
x_sred2 = sum(x)/N;
disp(['x_sred1 = ' ,string(x_sred1), 'x_sred2 = ' ,string(x_sred2)])
%average value loop for
l=length(x);
s_x=0;
for i=1:l
s_x=s_x+x(i);
end
x_sred3=s_x/N;
disp(['x_sred3 = ' ,string(x_sred3)])
3 Comments
Mathieu NOE
on 6 Mar 2024
No , the code is correct in its principle, but your for loop demonstrate that this method is accumulating more errors than the two first methods
with the choosen parameters , your sum should be zero , but you see actually some difference (as tiny numbers) because of round off accumated errors.
now if you can make a small change in your parameters to get a sum that is not (almost) zero , then all 3 computations are very close.
here for example I simply change N from 1200 to 1150 and I get :
"x_sred1 = " "0.056223" "x_sred2 = " "0.056223"
"x_sred3 = " "0.056223"
or N = 1200 and fp = 5000 (to increase time accuracy)
"x_sred1 = " "0.1825" "x_sred2 = " "0.1825"
"x_sred3 = " "0.1825"
VBBV
on 8 Mar 2024
@Joanna Zajac, It is something to do with property of sin function for specific values in input array
N = 1200;
A = 2;
fx = 5;
fp = 1000;
dt = 1/fp;
t = dt*(0:N-1);
x = A*(2*pi*fx*t);
x_sred1 = mean(x) %average value
x_sred2 = sum(x)/N
disp(['x_sred1 = ' ,string(x_sred1), 'x_sred2 = ' ,string(x_sred2)])
%average value loop for
% l=length(x);
s_x=0;
for i=1:numel(x)
s_x=s_x+x(i);
end
x_sred3=s_x/N;
disp(['x_sred3 = ' ,string(x_sred3)])
Answers (1)
Image Analyst
on 6 Mar 2024
Edited: Image Analyst
on 6 Mar 2024
This is round-off error, a form of quantization error. See
and
for explanations.
They should have taught you this in your numerical analysis class or linear algebra (matrix) class. Hopefully you have taken such a class in college.
0 Comments
See Also
Categories
Find more on Linear Algebra 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!