create a loop which adds all the previous values in matlab

You can use the classical iterative approach to solve this problem as follows:

main.m
n = 10; % number of iterations
sum = 0; % initialize sum

for i = 1:n
    sum = sum + i;
end

disp(sum); % print the sum
121 chars
9 lines

In this loop, we start with sum = 0, and then in each iteration, we add the index i to this sum. Finally, the loop is terminated when the index reaches n. You can increase or decrease the value of n and then run the loop to check if it's working correctly.

related categories

gistlibby LogSnag