If Statement for a Table

조회 수: 7 (최근 30일)
Qais Salaita
Qais Salaita 2022년 6월 3일
편집: Qais Salaita 2022년 6월 3일
Hello, since I have just shifted my work from excel to matlab due to the data size I am trying to write an if statement that is derived from an already existing excel if statement.
the statement that I wrote is:
h= height(t);
t.Self_cons= zeros(h, 1);
num_rows = size(t.InverterTimestamp,1);
for i=1:1:num_rows
if t.PowerSum>0
if t.SurplusPower<-(t.PowerSum)
t.Self_cons=0;
elseif t.SurplusPower<0
t.Self_cons= t.PowerSum -abs (t.SurplusPower);
elseif t.SurplusPower>=0
t.Self_cons= t.PowerSum;
else
t.Self_cons=0;
end
end
end
yet all of the t.Self_cons rows remain 0 for all the data set.
There are no errors in the code according to Matlab.
My expirience in Matlab is minimal and I need help in this regards
Edit: The comment Below Solved the issue that i had
  댓글 수: 1
Johan
Johan 2022년 6월 3일
With your current code you are comparing arrays of data. If I take a simple example with two randomly fillled arrays
t.example = rand(5,1);
t.compare = rand(5,1);
t.example
ans = 5×1
0.7741 0.4071 0.1359 0.7865 0.1325
t.compare
ans = 5×1
0.5995 0.5842 0.0402 0.4260 0.3876
t.example > t.compare
ans = 5×1 logical array
1 0 1 1 0
You can see that some match the comparison and some don't. If I put this comparison in an if statement I assume the if will only look at the first value of the array, thus you will always have the same outcome in your loop because you compare the same arrays of data at every step.
To fix your loop you can index your data array inside your for loop and run over all your data:
for i_loop=1:1:num_rows
if t.PowerSum(i_loop)>0
if t.SurplusPower(i_loop)<-(t.PowerSum(i_loop))
t.Self_cons(i_loop)=0;
elseif t.SurplusPower(i_loop)<0
t.Self_cons(i_loop)= t.PowerSum(i_loop) -abs(t.SurplusPower(i_loop));
elseif t.SurplusPower(i_loop)>=0
t.Self_cons(i_loop)= t.PowerSum(i_loop);
else
t.Self_cons(i_loop)=0;
end
end
end
Or you can make a logic arrays of your condition and change your data accordingly:
t.new = zeros(5,1);
logic_mask = t.example > t.compare;
% put 1 at the indices where my condition is met
t.new(logic_mask) = 1;
t.new % We see that the values of t.new where the logic array logic_mask is one have been changed
ans = 5×1
1 0 1 1 0
% The second statement of your loop could be something like this:
logic_mask = t.SurplusPower(i_loop)<0;
t.Self_cons(logic_mask)= t.PowerSum(logic_mask) -abs(t.SurplusPower(logic_mask));
I hope this helps,
Johan

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by