How to calculate repeated calculation using LOOP?
4 views (last 30 days)
Show older comments
I have 2 tables as below:
NetCh - has 12 column (var1 var2 ... var12) and 9 rows
yPeriod1 - has 1 column and 9 rows
I would like to calculation within each column in NetCh for 12 times and write 12 results (Der1 Der2 .. Der12) in a new table.
Now I have to do by mannually all of them.
Can you please tell me make it small code using LOOP.
NetCh1 = table(NetCh.Var1)
NetCh1.Hangal = (NetCh1{:,1}).*(yPeriod1{:,1})
NetCh1.Haliun = (yPeriod1{:,1}).^2
Tr1 = sum(yPeriod1{:,1})
Br1 = sum(NetCh1{:,1},'omitnan')
Hr1 = sum(NetCh1.Hangal,'omitnan')
Qr1 = sum(NetCh1.Haliun)
Der1 = Br1*Qr1-Tr1*Hr1
NetCh2 = table(NetCh.Var2)
NetCh2.Hangal = (NetCh2{:,1}).*(yPeriod1{:,1})
NetCh2.Haliun = (yPeriod1{:,1}).^2
Tr2 = sum(yPeriod1{:,1})
Br2 = sum(NetCh2{:,1},'omitnan')
Hr2 = sum(NetCh2.Hangal,'omitnan')
Qr2 = sum(NetCh2.Haliun)
Der2 = Br2*Qr2-Tr2*Hr2
0 Comments
Accepted Answer
Karim
on 12 Nov 2022
Edited: Karim
on 13 Nov 2022
Note that you can add data (e.g. a .mat file) to your question using the paperclip symbol. Without it is is difficult to validate the process.
To give you an idea on how a for loop could look like:
% EDIT, updated the routine after the OP provided example data
NetCh = readtable("https://nl.mathworks.com/matlabcentral/answers/uploaded_files/1190448/NetCh.xlsx")
% skip 1 column as it seems to be the vaiable name
numVar = size(NetCh,2)-1;
yPeriodFor = (1:9)';
% create an array to save the results
Der = zeros(numVar,1);
for i = 1:numVar
% extract the current column
% +1 to skip the first column
currData = NetCh{:,i+1};
% do the processing
Hangal = currData.*yPeriodFor;
Haliun = yPeriodFor.^2;
% evaluate the sum's
Tr = sum(yPeriodFor);
Br = sum(currData,'omitnan');
Hr = sum(Hangal,'omitnan');
Qr = sum(Haliun);
% evaluate and save the result
Der(i) = Br*Qr-Tr*Hr;
end
% display the results
Der
3 Comments
Karim
on 12 Nov 2022
I made an update to the answer, the reason for the error is that the first column contains text... you need to skip this column in the for loop. See the adjusted answer.
More Answers (0)
See Also
Categories
Find more on Data Type Conversion 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!