For loop not calculating properly

5 visualizaciones (últimos 30 días)
Kyle Donk
Kyle Donk el 14 de En. de 2020
Comentada: Image Analyst el 18 de En. de 2020
My instructions are to calculate the result and absolute error for each partial sum: N = 10, 160, and 640. I am supposed to be getting the sum and error value for each N, but I am only getting the sum and error values for 640 only. I do not know why this is the case, as N equals 10, 160 and 640.
PLEASE DO NOT GIVE ME A COMPLETE ANSWER. I WOULD JUST LIKE TO KNOW WHAT I AM DOING WRONG. THANK U.
This is what I have so far:
for N=[10 160 640]
sum=0;
for n=1:N
y=1/n^2
sum=sum+y;
end
sum
error=((pi^2)/6)-sum
end
  3 comentarios
Kyle Donk
Kyle Donk el 14 de En. de 2020
I have to use a for loop for this and most of the time we are not allowed to use Matlab's built-in functions.
Image Analyst
Image Analyst el 14 de En. de 2020
Kyle, did you see my Answer (below)??? I already gave you hints for solving it using your current for loop.

Iniciar sesión para comentar.

Respuesta aceptada

Image Analyst
Image Analyst el 14 de En. de 2020
Don't use sum as the name of your variable since that's already the name of a built-in function.
You need to assign N outside the loop and then get it inside the loop (method 1), OR use a counter to get the iteration number (method 2).
N=[10 160 640] % Method 1
for k = 1 : length(N)
thisN = N(k)
% more code to compute this sum.
end
Then you need to compute thisSum(k) and also index the error with the iteration loop counter:
thisError(k) = ((pi^2)/6) - thisSum(k);
so that you will have an error value for every iteration.
  1 comentario
Image Analyst
Image Analyst el 18 de En. de 2020
Kyle, did this solve it? If so, please accept this answer, and any other answers for your other questions/threads. Thanks in advance.

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