如何计算MATLAB中的特定数字?

时间:2015-11-03 04:09:06

标签: matlab

excel文件中的两列;第一列包含年(Y),第二列包含值(MWS)。第二列有三种值:大于零,零和-999。我想算一下:

  • 每年有多少个零,

  • 一年中有多少值超过零。

我尝试了以下代码,它们给了我而不是数。

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

任何帮助都会得到帮助。

祝你好运

2 个答案:

答案 0 :(得分:2)

使用内置的accumarray之类的东西会起作用并避免需要循环。

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))];

如果您仍想使用循环,则原始代码几乎是正确的,但您只是错误地将MWS编入索引。以下应该有效。

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

答案 1 :(得分:1)

乍一看,我在代码中看到了以下问题:

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

让我们通过调整你的逻辑来修复代码。我还没有对以下内容进行过测试,但它应该有效。

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