How to Sum a loop and Then Loop that Sum

16 views (last 30 days)
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

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!