If Statement for a Table
7 views (last 30 days)
Show older comments
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 Comment
Johan
on 3 Jun 2022
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
t.compare
t.example > t.compare
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
% 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
Answers (0)
See Also
Categories
Find more on Data Type Identification 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!