how to sum a vector without sum function
54 visualizzazioni (ultimi 30 giorni)
KL il 3 Set 2018
Modificato: KL il 4 Nov 2020
Your idea of using for loop is correct but you should use it to calculate the sum not the mean.
If there's a vector A = [1,2,3,4,5], how would you calculate the sum? By adding its elements with each other, right? It's pretty much the same here.
- create a resuting variable and initilize it to 0
result_sum = 0;
- use the for loop to index through A and add the current element to the above variable
result_sum = result_sum + A(i);
- once you are done with the for loop calculate mean by diving it with N (just like you've done but outside the loop)
Dennis il 3 Set 2018
If the only requirement is to not use sum, i'd like to suggest to use cumsum instead!
As an alternative you could use a loop.