Indexing table rows by comparing values ​​between two cells

enter image description here

I have a table similar to the application above. Column A and column B contain some elements in terms of an array of cells. I want to create a third column (Level) as a summary column; based on the following logic.

  • A row for which cell value A = cell B value will be marked as 1. (In the third row, column value A = column value B = 3, therefore marked as 1).

  • Then the previous value will be deleted from all cells in column A; and step 1 will be repeated until all lines are marked. (In the second step, 3 will be deleted from all cells, therefore, both rows 1 and row 2 will be marked as 2; the final step, the elements {1,2} will be deleted from the last row as a result of level 3)

I use the cell2mat and setdiff functions to compare values ​​across cells, but I cannot create the two logical steps above to successfully run my code. I just started learning MATLAB, any help would be much appreciated.

+4
source share
2 answers

Here is the simplest answer that I could use, using a single while loop and assuming the cells Aboth Bcontain row vectors:

Level = zeros(size(A));
index = cellfun(@isequal, A, B);
while any(index)
  Level(index) = max(Level)+1;      
  A = cellfun(@(c) {setdiff(c, unique([A{index}]))}, A);
  index = cellfun(@isequal, A, B);
end

zeroes Level , A, . index, A B, cellfun isequal. , any index. Level Level . A concatenated unique, unique([A{index}]). ( cellfun), A, A . index , .

:

A = {[1 2 3]; [2 3]; 3; [1 2 3 4]};
B = {[1 2]; 2; 3; 4};

:

Level =

     2
     2
     1
     3
+2

, , .

% your testdata
A = {[1 2 3]
    [2 3]
    3
    [1,2,4]};
B = {[1 2]
    2
    3
    4};


Level = NaN(numel(B),1);
temp = A; % copy of A that we are going to remove elements from
k = 0; % loop couter
while any(isnan(Level)) % do until each element of Level is not NaN
    k = k+1; % increment counter by 1

    % step 1
    idx = find(cellfun(@isequal,temp,B)); % determine which cells are equal
    Level(idx) = k; % set level of equal cells

    % step 2
    for k = 1:numel(idx) % for each cell that is equal
        %remove values in B from A for each equal cell
        temp = cellfun(@setdiff,temp,repmat(B(idx(k)),numel(B),1),'UniformOutput',0);
    end   
end
+1

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


All Articles