Nested for loop for a matrix
1 view (last 30 days)
Show older comments
I need to use nested for loop.Code is given below. What I need to perform is for every value of T (j loop used) i need to evaluate E with all values of Am, Bm, Cm,Mm,xm etc(i loop used). My major doubt is how to apply for loop for input values of xm as for every value of T(j loop)it should solve for 3 values of xm; then for next T value nit should take next 3 inputs.If I could get some idea how it can be done error free?
Am= [5.01 78.54 59.07];
Bm= [0 31989.4 31989.4];
Cm= [291.15 298.15 298.15];
Mm= [127.9123 18.015 253.81];
xm=[0.5096 0.5092 0.5087;
0.0963 0.0964 0.0965;
0.3941 0.3944 0.3948];
T=[394.15 399.15 404.15 ];
N=length(T)
M=length(Am)
E=zeros(1,3);
for j=1:N
em=zeros(1,3);
e=zeros(1,3);
D= zeros(1,3);
for i=1:M
em(i)= Am(i)+Bm(i)*((1/T(j))-(1/Cm(i)))
D(i)=xm(i)*Mm(i)
e(i)= D(i)*em(i)
end
E(j)=sum(e(i))/sum(D(i))
end
0 Comments
Answers (1)
Nehemiae
on 8 Feb 2023
From what I can understand, you are able to correctly set the array , but D is not set correctly as it is required that for each iteration a set of 3 values from needs to be used.
I'm going to assume that for each iteration in j (each value of T) that the corresponding row from is required. However, I would like to point that in the last line of the loop j, where E is being assigned, that only the 3rd element of e and D are divided, as after the nested loop, the value of i will be 3. So here again I assume that it is required that the sum of the 3 elements of e and D need to be divided.
Do see if the following code meets your expectation.
Am = [5.01 78.54 59.07];
Bm = [0 31989.4 31989.4];
Cm = [291.15 298.15 298.15];
Mm = [127.9123 18.015 253.81];
xm = [0.5096 0.5092 0.5087;
0.0963 0.0964 0.0965;
0.3941 0.3944 0.3948];
T = [394.15 399.15 404.15];
N = length(T);
M = length(Am);
E = zeros(1, 3);
for j = 1 : N
em = zeros(1, 3);
e = zeros(1, 3);
D = zeros(1, 3);
for i = 1 : M
em(i) = Am(i) + Bm(i) * ((1 / T(j)) - (1 / Cm(i)));
D(i) = xm(j + M * (i - 1)) * Mm(i); % Use column-major indexing of xm
e(i) = D(i) * em(i);
end
E(j) = sum(e) / sum(D); % Suggested that the sum of elements in e and D need to be divided and hence removing indexing variable
end
E
Please refer to the Array Layouts documentation to understand how matrices are stored in memory, as well the sum documentation to see how the sum of elements of an array is calculated.
0 Comments
See Also
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!