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 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 28 Feb 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.

More Answers (1)

Bader Ben-Slimane
Bader Ben-Slimane on 28 Feb 2017
Sum=0;
for k=1:25;
Sum = Sum + k.^2;
end
disp(sum)
  3 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!