MATLAB: how to count the frequency of numbers in a column, in continuous blocks

I have a matrix ain Matlab that looks like this:

a = zeros(10,3); 
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0

I would like to get an array of cells with the number of times that each number appears in the column. In addition, it must be ordered depending on the value of the item, regardless of the column number. In the above example, I would like to get a cell:

b = {[5],[4,3],[3]}

Because number 1 appears once 5 times, number 2 twice in blocks 4 and 3, and number 3 once 3 times. As you can see, recursions are ordered according to the value of the element, not the number of the column in which the elements appear.

+4
source share
3 answers

, -, , :

v = reshape(padarray(a, [1 0]), [], 1);
% Or if you don't have the Image Processing Toolbox function padarray...
v = reshape([zeros(1, size(a, 2)); a; zeros(1, size(a, 2))], [], 1);

, 1 , :

endPoints = find(diff(v) ~= 0);  % Find where transitions to or from 0 occur
spans = endPoints(2:2:end)-endPoints(1:2:end); % Index of transitions to 0 minus
                                               % index of transitions from 0

, , , :

b = accumarray(v(endPoints(1:2:end)+1), spans, [], @(v) {v(:).'}).';

:

b =

  1×3 cell array

    [5]    [1×2 double]    [3]

:

spans (.. b{2} [3 4] [4 3]). , . b:

[vals, index] = sort(v(endPoints(1:2:end)+1));
b = accumarray(vals, spans(index), [], @(v) {v(:).'}).';
+3

- . diff , :

b = [zeros(1,size(a,2)); a; zeros(1,size(a,2))];
idx = diff(b)~=0;
block_values = b(idx);
block_lengths = diff([0; find(idx)]);

, ,

c = accumarray(block_values(block_values~=0), block_lengths(block_values~=0), [], @(x) {x}).';
+3
b = {}
for i = 1:ncolumns
    for n = 1:nnumbers
        b{i}(n) = sum(a(:,i) == n)
    end
end

(Note that this puts zeros for numbers in which the number is 0, but otherwise I don't see how else you could find out what value is counting)

0
source

Source: https://habr.com/ru/post/1678718/


All Articles