Grouping users into 3 groups using for loop and if statements

조회 수: 11 (최근 30일)
Magsud Hasanov
Magsud Hasanov 2022년 6월 13일
댓글: Voss 2022년 6월 14일
Hello, I am trying to group 75 different users into 3 groups by usage of electricity : Consumers, Prosumers and Producers. [ Prosumer = Consumption + Production].
The code I am writing is as follows:
load syncedData.mat %loading data - 3 tables (EdSynced, EgSynced and PSynced)
sum(EdSynced{:,2}) % this is how I get the demand (consumption) data
sum(EgSynced{:,2}) % this is how I get the generation data
% for pure consumers the EgSynced variable is full of zeros, so the sum is
% zero. And the same applies for pure producers vice versa.
class_code = zeros(75,3) % creating a matrix for further classification - 75 users and 3 groups
for i= 2:76 % in EdSynced and EgSynced these users are variables from 2 to 76 (75 various users)
for k=1:75 %
consume = sum(EdSynced{:,i});
generates = sum(EgSynced{:,i});
if consume > 0 && generates >0
class_code(k,1) = 1;
elseif consume ==0 && generates >0
class_code(k,2) = 1;
else
class_code(k,3) = 1;
end
end
end
After that I convert the matrix into table:
classes = ["Prosumer","Producer","Consumer"];
class_code = array2table(class_code,'VariableNames',classes)
But, unfortunately my code doesn't work properly. Could you please suggest a fix for it?
It outputs (the first segment of code) the matrix full of ones.
Thank you very much in advance!

채택된 답변

Voss
Voss 2022년 6월 13일
It seems like you should not be using two loops. That'll do the counting for every combination of i and k. Instead it seems like you want to do one loop (over i or k) where k=i-1.
class_code = zeros(75,3) % creating a matrix for further classification - 75 users and 3 groups
for ii = 2:76 % in EdSynced and EgSynced these users are variables from 2 to 76 (75 various users)
consume = sum(EdSynced{:,ii});
generates = sum(EgSynced{:,ii});
if consume > 0 && generates > 0
class_code(ii-1,1) = 1;
elseif consume == 0 && generates > 0
class_code(ii-1,2) = 1;
else
class_code(ii-1,3) = 1;
end
end
Of course, if that's how it should be, it can be done with zero loops.
  댓글 수: 2
Magsud Hasanov
Magsud Hasanov 2022년 6월 14일
Thank you very much! The code that I used and it worked was something like this
class_code = zeros(75,3)
for k =1:75
consume = sum(Ed{:,k+1});
generates = sum(Eg{:,k+1});
if generates>0 && consume == 0
class_code(k,1) = 1;
elseif consume >0 && generates ==0
class_code(k,2) = 1;
else
class_code(k,3) = 1;
end
end
clear generates consume k
The idea is the same as yours, so I guess both give the same output.
Thank you very much!
Voss
Voss 2022년 6월 14일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by