开发者

Need to analyze a set of vectors with 0 and positive integers

I am using Matlab, and I have a 1x200 vector of numbers.

I need to assign a "score" to the set of numbers by following these rules:

  1. If there are 2 or 3 or 4 consecutive positive numbers, then开发者_运维知识库 0.5 points
  2. If there are five or more consecutive positive numbers, then 1.0 points
  3. If there isn't any consecutive positive number, for example: 0 0 0 6 0 0, then 0.0 point. (ignore it, consider that positive number as zero)
  4. If there is only one zero in the middle of a run of positive integers, then ignore that zero (consider it as a positive integer)
  5. If there are two or more consecutive zeroes, that breaks the run of consecutive positive numbers.

Example: 30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 (2.0 points total)

At the end, there should be a tally of the points.

Are there any useful functions for this type of problem?


This is based on my understanding of the question, as noted in my question above. I've "unsuppressed" all output, so you can see what's going on.

%Rules:
%1. If there are 2 or 3 or 4 consecutive positive numbers, then 0.5 point
%2. If there are five or more consecutive positive numbers, then 1.0 point
%3.  And if there isn't any consecutive positive number, for example: 
%   0 0 0 6 0 0, then 0.0 point. (ignore it, consider that positive 
%   number as zero)
%4. if there is only one zero in the middle of positive integers = ignore 
%   that zero (consider it as a positive integer)
%5. If there are two or more consecutive 0, THEN no point.

%testData = [0 30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 1 2 0 1 2 0 ];
testData = [30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 ];
posa = testData>0;
%add 0s at each end so that the diffs at the ends work.
diffa = diff([0 posa 0])
starts = find(diffa ==1)
ends = find(diffa==-1)

% Rule 4 if any end (-1) is immediately followed by a start, that means that there 
%   is a 0 in the middle of a run.  substitute a 1 in the position and recalc.
midZeroLengths = starts(2:end) - ends(1:(end-1));
%pad to account for the fact that we only compared part.
midZeroLengths = [midZeroLengths 0];
if any(midZeroLengths == 1);
    testData(ends(midZeroLengths==1)) = 1;
    posa = testData>0;
    %add 0s at each end so that the diffs at the ends work.
    diffa = diff([0 posa 0])
    starts = find(diffa ==1)
    ends = find(diffa==-1)  
end

runs = ends-starts
halfs = (runs > 1) & (runs < 5)
wholes = (runs > 4)
final = sum(halfs)*0.5 + sum(wholes)


How about:

str = repmat('a', 1, numel(testData));
str(testData > 0) = 'b';
m = regexp(str, 'b+(ab+)*', 'match');
n = cellfun(@numel, m);
score = 0.5 * sum(n >= 2 & n <= 4) + 1.0 * sum(n >= 5);

Note that I haven't run this, so there may be errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜