find the sum of 1-10 numbers, store the results in a array in matlab

To find the sum of numbers from 1 to 10 and store the results in an array in MATLAB, you can use a for loop along with an indexing variable to store the individual sums in the array. Here's how you can do it:

main.m
% Initialize an array to store the sums
sumArray = zeros(1, 10);

% Calculate the sums and store them in the array
for i = 1:10
    sumArray(i) = sum(1:i);
end

% Display the array
disp(sumArray);
197 chars
11 lines

In the above code, sumArray is initialized as a zero-filled array of size 1x10. Each iteration of the for loop calculates the sum of numbers from 1 to the current index value (i) using the sum function, and assigns it to the corresponding element in sumArray. Finally, the contents of sumArray are displayed using the disp function.

This will output the array sumArray which contains the sums of numbers from 1 to 10:

main.m
1     3     6    10    15    21    28    36    45    55
56 chars
2 lines

Note: Since the sum of numbers from 1 to n can be calculated using the formula (n * (n + 1)) / 2, you can avoid using a loop altogether in this particular case by directly applying the formula.

related categories

gistlibby LogSnag