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.m197 chars11 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.m56 chars2 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.
gistlibby LogSnag