MATLAB: Im trying to find the summation from k=1 to 25, with the equation being k^2. This is the code, how do i get it do only display the final number only, not the ones in between
MATLAB
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
Best Answer
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 calleddisp and therefore matlab understandsdisp(Sum) as indexing into thedisp variable instead of calling thedisp 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 yourSum variable which is extremely similar to thesum function. Other typical names that cause problems: max, min, diff.
Somewhere earlier in your code you have avariable named‘sum’ that is ‘overshadowing’ thesum function. Rename the variable to something other than‘sum’ (or the name of any other MATLAB function) and the problem will disappear.
Best Answer