How to calculate repeated calculation using LOOP?
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
Karim
2022년 11월 12일
편집: Karim
2022년 11월 13일
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
Karim
2022년 11월 12일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!