Search code examples
matlabmatrixmaxcontinuations

sum of continuous values in matlab


I need to calculate the following in matlab.

EDIT EDIT: I alway have a 16 x 3 matrix. 16 rows and 3 columns. The 3 columns represent R,G,B and the 16 rows represent points. From 1-16. An example matrix looks like this:

1 1 1
-1 0 0
0 0 1
1 0 0
-1 0 0
1 0 -1
1 1 1
1 1 1
0 0 0
-1 0 1
1 0 0
0 0 1
1 0 1
0 0 0
0 0 0
1 0 1

Now I need to know are there 11 coherently rows which have min. 1 value ~= 0 in each column? In the above example the first 8 rows and the last row have in each column min 1 value and are coherently. So this 9 rows are the max coherently rows without a complete zero row between.

Sry that my first post wasn't correct.

I've do that with a really poor for-solution. Is there a faster way (vectorized) to do that?

for i=1:16
   for j=0:16
      if i+j > 16
         value = (i+j)-16;
      else
         value = i+j;
      end
      if table(value,1) ~= 0 || table(value,2) ~= 0 || table(value,3) ~= 0
         equal = equal + 1;
         if equal >= 11
            copy(y,x) = 1;
            equal = 0;
            break;
         end
         else
            equal = 0;
         end
      end
   end
end

And the 16 points are circular. This min the first point and the last point connect.

Thanks for help and sry for the confusing.


Solution

  • This counts the number of coherent rows with at least one none-zero entry without circularity:

    B = ~(A==0);
    idx = find(sum(B,2) == 0);
    result = max([idx;size(A,1)+1] - [0;idx]) - 1;
    

    Now you can check whether result is bigger than 11.

    Another way would be:

    B = ~(A==0);
    C = bwconncomp(sum(B,2)>0);
    num = cellfun(@numel,C.PixelIdxList);
    result = max(num);
    

    EDIT 2: To account for circularity, i.e. rows at the beginning and the end should be counted as coherent, you could do

    B = ~(A==0);
    idx = find(sum(B,2) == 0);
    result = max([idx;size(A,1)+idx;size(A,1)+1] - [0;idx;size(A,1)+idx]) - 1;
    

    EDIT: I edited the result-line in the first solution according to Knedlsepp's comments.