How to Sum a loop and Then Loop that Sum

2 visualizaciones (últimos 30 días)
Todd Trainor
Todd Trainor el 9 de Mzo. de 2019
Comentada: Guillaume el 10 de Mzo. de 2019
Sorry for the confusing title,
So lets say i have 2 sets of data;
a= 4, 8, 9, 11, 13
d = 0.2, 0.3, 0.5, 0.6, 0.8
the equation i want results from is: a * d * (1 - (d / (2 * a) ))
so i want to get the sum of all these equations together:
a1 * d1 * (1 - (d1 / (2 * a1) ))
a2 * d1 * (1 - (d1 / (2 * a2) ))
a3 * d1 * (1 - (d1 / (2 * a3) ))
a4 * d1 * (1 - (d1 / (2 * a4) ))
a5 * d1 * (1 - (d1 / (2 * a5) ))
so the sum of all of these would be my first value.
The next value would be the sum of all these equations:
a1 * d2 * (1 - (d2 / (2 * a1) ))
a2 * d2 * (1 - (d2 / (2 * a2) ))
a3 * d2 * (1 - (d2 / (2 * a3) ))
a4 * d2 * (1 - (d2 / (2 * a4) ))
a5 * d2 * (1 - (d2 / (2 * a5) ))
The next value the sum of these:
a1 * d3 * (1 - (d3 / (2 * a1) ))
a2 * d3 * (1 - (d3 / (2 * a2) ))
a3 * d3 * (1 - (d3 / (2 * a3) ))
a4 * d3 * (1 - (d3 / (2 * a4) ))
a5 * d3 * (1 - (d3 / (2 * a5) ))
and so on.. until i have 5 values
Thank you

Respuesta aceptada

Guillaume
Guillaume el 9 de Mzo. de 2019
a = [4, 8, 9, 11, 13];
d = [0.2, 0.3, 0.5, 0.6, 0.8];
d = d.'; %transpose d so it's a column vector
result = a .* d .* (1 - d ./ (2*a))
columns of result correspond to the elements of a, rows to the elements of d. This uses the implicit expansion introduced in R2016b
  2 comentarios
Todd Trainor
Todd Trainor el 9 de Mzo. de 2019
Hello thank you for your answer,
If i were to sum these up using this code, how could i then put these 5 values into a vector?
for x = 1:5
sum(result(x,1:5))
end
Guillaume
Guillaume el 10 de Mzo. de 2019
You don't need a loop
result = a .* d .* (1 - d ./ (2*a));
sumresult = sum(result, 2) %sum across the columns

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by