Im trying to find the summation from k=1 to 25, with the equation being k^2. This is my code, how do i get it do only display the final number only, not the ones in between?

6 visualizaciones (últimos 30 días)
I tried disp(Sum) at the end, but tells me that index exceeds matrix dimensions. Sum=0;
for k=1:25;
Sum = Sum + k.^2
end

Respuesta aceptada

Guillaume
Guillaume el 28 de Feb. de 2017
If you use this exact code:
Sum=0;
for k=1:25;
Sum = Sum + k.^2
end
disp(Sum)
and you get the error "Index exceeds matrix dimension", there can be only one reason: You have created a variable called disp and therefore matlab understands disp(Sum) as indexing into the disp variable instead of calling the disp function.
clear disp
would fix the problem. And this is a lesson to you not to name your variables the same as common matlab functions. You nearly did the same with your Sum variable which is extremely similar to the sum function. Other typical names that cause problems: max, min, diff.

Más respuestas (1)

Bader Ben-Slimane
Bader Ben-Slimane el 28 de Feb. de 2017
Sum=0;
for k=1:25;
Sum = Sum + k.^2;
end
disp(sum)
  3 comentarios
Guillaume
Guillaume el 28 de Feb. de 2017
The both of you, please use the {} Code button to format code as code.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by