# how to sum a vector without sum function

54 visualizzazioni (ultimi 30 giorni)
nathan Short il 3 Set 2018
Risposto: Ameer Hamza il 4 Nov 2020
function Mean = mean_strength(StrengthVector)
N = numel(StrengthVector);
x = sum(StrengthVector);
for i = 1:N
Mean = (1/N)*(x);
end
I need to change my code so I don't use the in built Matlab sum function.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (5)

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)
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Dennis il 3 Set 2018
If the only requirement is to not use sum, i'd like to suggest to use cumsum instead!
A=cumsum(StrengthVector);
x=A(end);
As an alternative you could use a loop.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Matt J il 3 Set 2018
Modificato: Matt J il 3 Set 2018
You can do all sorts of crazy things,
function Mean = mean_strength(StrengthVector)
N = numel(StrengthVector);
if N==1
Mean = StrengthVector;
else
Mean = StrengthVector(1)/N + (N-1)/N*mean_strength( StrengthVector(2:end) );
end
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Matt J il 3 Set 2018
x = log( prod(exp(StrengthVector)) );
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Ameer Hamza il 4 Nov 2020
x = 1:10;
s = x*ones(size(x)).'
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by