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?

조회 수: 4 (최근 30일)
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

채택된 답변

Guillaume
Guillaume 2017년 2월 28일
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.

추가 답변 (1개)

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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by