Reputation: 111
Two columns in an excel file; first column contains year(Y) and the second column contains values(MWS). Second column has three kinds of values: more than zero, zero and -999. I am trying to count:
how many zeros are in each year,and
how many values are more than zero in a year.
I have tried the following codes, which give me sum instead of count.
yy = unique(Y);
ny = max(Y)-min(Y)+1;
X1 = zeros(ny,1);
X2 = zeros(ny,1);
for i = 1:ny
X1(i) = sum(MWS((Y == yy(i))==0));
end
for i = 1:ny
X2(i) = sum(MWS((Y == yy(i))>=0));
end
Any help would be apprecaited.
Best regards
Upvotes: 2
Views: 93
Reputation: 2225
Something like this, using the inbuilt accumarray would work and avoids needing the loops.
Y = [2013, 2013, 2013, 2014, 2014, 2014, 2015, 2015, 2015];
MWS = [0, 0, 1, 0, 0, 0, 1, 1, 1];
[unique_years, ~, indexes] = unique(Y);
numZerosInYear = [unique_years', accumarray(indexes', MWS, [], @(x) sum(x == 0))];
numAboveZeroInYear = [unique_years', accumarray(indexes', MWS, [], @(x) sum(x > 0))];
If you still want to use loops, your original code is almost correct, however you're just indexing MWS
incorrectly. The following should work.
for i = 1:ny
X1(i) = sum(MWS(Y == yy(i)) == 0);
end
for i = 1:ny
X2(i) = sum(MWS(Y == yy(i)) >= 0);
end
Upvotes: 2
Reputation: 9075
I see the following problems in your code at first glance:
yy = unique(Y);
ny = max(Y)-min(Y)+1; %this will not be correct if Y has non-consecutive years.
X1 = zeros(ny,1);
X2 = zeros(ny,1);
for i = 1:ny
% I do not understand what you trying to do on the following line.
% You are creating a logical vector which has wherever Y takes the
% value = yy(i), fair enough. However, you test for equality with 0,
% which places ones wherever Y ~= yy(i). MWS(Y == yy(i))==0) returns
% all those values (not ones, actual values). Then you sum the
% values. Hence you are not getting the count, but getting a sum.
X1(i) = sum(MWS((Y == yy(i))==0));
end
for i = 1:ny
% I think you can figure this out now. One mistake here is that you
% test for >=0 but you state that you want values greater than zero.
% I have corrected that in my code.
X2(i) = sum(MWS((Y == yy(i))>=0));
end
Lets fix the code now by tweaking your logic. I haven't tested the following, but it should work.
yy = unique(Y);
ny=numel(yy);
X1 = zeros(ny,1);
X2 = zeros(ny,1);
for i = 1:numel(yy)
X1(i) = sum(MWS(Y==y(i))==0) %how many zeros in year y(i)
X2(i) = sum(MWS(Y==y(i))>0) %how many > than zero in year y(i)
end
Upvotes: 1