通过比较两个单元格之间的值来索引表的行

时间:2017-09-14 14:54:19

标签: matlab for-loop indexing comparison

enter image description here

我有一张上面附件的表格。 A列和B列包含一些单元阵列的元素。我想创建第三列(Level)作为结果列;基于以下逻辑。

  1. 单元格A的值=单元格B的值将被标记为1的行。 (在第3行中,A列的值= B列的值= 3,因此标记为1)。

  2. 接下来,将从全部删除前面的值 A列的细胞;并且将重复步骤1直到全部 行标记。 (在第二步中,将从全部删除3 因此,第1行和第2行都将被标记为2; 最后一步,元素{1,2}将从最后一行中进一步删除 结果为3)

  3. 我正在使用 cell2mat setdiff 函数来比较单元格中的值,但我无法构建上述2个逻辑步骤以成功运行我的代码。我刚开始学习MATLAB,非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

这是我能提出的最简单的答案,使用单个while循环并假设AB的单元格包含行向量:

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

上述代码首先初始化与Level大小相同的zeroes A矩阵,以存储关卡值。然后,它使用logical indexcellfun找到index ABindex之间匹配的单元格内容的isequal Level。只要Level指示loop次匹配,它就会继续anyA中的相应索引设置为unique([A{index}])中的当前maximum value加1。来自cellfun的所有匹配单元格内容均为concatenatedA找到unique个值。然后使用set difference操作(以及A)从index中的每个单元格中删除匹配值,并使用其余值覆盖A = {[1 2 3]; [2 3]; 3; [1 2 3 4]}; B = {[1 2]; 2; 3; 4}; 。然后计算匹配的新Level = 2 2 1 3 并重新开始循环。

根据您的问题提供以下示例数据:

let calculate ~size_of_experiment:s ~number_of_buckets:n =
  let results = run_experiments s n in
  List.iter (fun x -> print_endline x) results;
  List.fold_left (fun x y -> x + (snd y)) 0 results

代码返回预期的级别向量:

Error: This expression has type (int * int) list
       but an expression was expected of type string list
       Type int * int is not compatible with type string

答案 1 :(得分:1)

不是我最好的工作,我认为可以摆脱内循环。

% 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
相关问题