How to Sum a loop and Then Loop that Sum

3 Ansichten (letzte 30 Tage)
Todd Trainor
Todd Trainor am 9 Mär. 2019
Kommentiert: Guillaume am 10 Mär. 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

Akzeptierte Antwort

Guillaume
Guillaume am 9 Mär. 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 Kommentare
Todd Trainor
Todd Trainor am 9 Mär. 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 am 10 Mär. 2019
You don't need a loop
result = a .* d .* (1 - d ./ (2*a));
sumresult = sum(result, 2) %sum across the columns

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by