MATLAB: Need help with summation in a while loop. i believe the argument inside of while is wrong, but i’m not sure how to fix. Assignment is to Write a while loop that assigns summedValue with the sum of all values from 1 to userNum.(assume userNum>=1).

function summedValue = SummationWithLoop(userNum)
x=1:1:userNum;
xSum=0;
k=1;
while (xSum<=userNum)
xSum = xSum+x(k);
k=k+1;
end

Best Answer

You don't need your variable x. k starts at one and increases by one with each iteration, so achieves the same thing as you are trying to do with the vector x. Just add k to your sum instead.
Also your while loop condition won't work properly, but I'll let you have a go at figuring that out.