How to use the sum of all the iterations of a value calculated in a for-loop to calculate another value within the same loop?

15 次查看(过去 30 天)
Hi, I am trying to calculate the species mass fractions (Wi) within a stream by dividing the species flow rate (Mi) by the overall mass flow rate (sum of all values of Mi). I have managed to calculate and save all the mass flow rates (mi), but I'm struggling with summing all those values to get the overall stream mass flow rate. Any help would be greatly appreciated.
for i = 1:50
Mi = M(i)*n(i); % species mass flow rate (g/h)
mi(i) = Mi;
Xi = n(i)/sum(n); % species mole fraction (no unit)
xi(i) = Xi;
Wi = Mi/sum(mi); % species mass fraction (no unit) - this is the denominator I'm struggling with
wi(i) = Wi;
end
  4 个评论
Jessica Hale
Jessica Hale 2022-9-20
So sorry, I meant something like this:
M = [2 3]
n = [8 9]
Mi_1 = M(1)*n(1)
Mi_2 = M(2)*n(2)
mi = [Mi_1 Mi_2]
mi_total = sum(mi)
Wi_1 = Mi_1/mi_total
Wi_2 = Mi_2/mi_total
wi = [Wi_1 Wi_2]
But I want to do this for when M and n are 50x1 arrays, and then calcuate Mi_1,..., Mi_50 and Wi_1,..., Wi_50 in a for loop.

请先登录,再进行评论。

回答(1 个)

Dyuman Joshi
Dyuman Joshi 2022-9-20
编辑:Dyuman Joshi 2022-9-20
Is using a loop necessary?
If yes, then my comment above should work -
M = [2 3];
n = [8 9];
for i = 1:2
mi(i) = M(i)*n(i); % species mass flow rate (g/h)
end
mi
mi = 1×2
16 27
wi=mi/sum(mi)
wi = 1×2
0.3721 0.6279
If no, then you can do without loop as well
mi1=M.*n
mi1 = 1×2
16 27
wi1=mi1/sum(mi1)
wi1 = 1×2
0.3721 0.6279
Verification, with the code you provided
Mi_1 = M(1)*n(1);
Mi_2 = M(2)*n(2);
Mi = [Mi_1 Mi_2]
Mi = 1×2
16 27
Mi_total = sum(Mi);
Wi_1 = Mi_1/Mi_total;
Wi_2 = Mi_2/Mi_total;
Wi = [Wi_1 Wi_2]
Wi = 1×2
0.3721 0.6279

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by