MATLAB单元函数根据条件查找单元阵列子集

问题描述 投票:0回答:1

给定[R G B]MATLAB值的单元格数组,我需要找到由满足条件的那些特定元素组成的子cell_array。 (使用细胞功能)。

我在想:

subset = cellfun(@(x) condition(x), superset, 'UniformOutput',false);

但是,对于满足条件的那些元素,这给出1,否则如预期的那样给出0。但我需要一个子集,由condition == 1的那些元素组成。请建议。

matlab cell anonymous-function cell-array
1个回答
1
投票
% Example Data
superset = {
    [0.983 0.711 0.000];
    [1.000 0.020 0.668];
    [0.237 1.000 1.000];
    [0.245 0.707 0.544];
    [0.000 0.000 0.000]
};

% Example Condition: RGB is Pure Black
subset_idx = cell2mat(cellfun(@(x) all(x == 0),superset,'UniformOutput',false));

% Subset Extraction
subset = superset(subset_idx);

允许您避免在每个单元数组元素上循环的替代方法:

% Example Data
superset = {
    [0.983 0.711 0.000];
    [1.000 0.020 0.668];
    [0.237 1.000 1.000];
    [0.245 0.707 0.544];
    [0.000 0.000 0.000]
};

% Convert Cell Array of Vectors to Matrix
superset = cell2mat(superset);

% Example Condition: G and B Greater Than 0.5
subset_idx = (superset(:,2) > 0.5) & (superset(:,3) > 0.5);

% Subset Extraction
subset = superset(subset_idx,:);

无论您喜欢什么方法,将条件应用于数据的每一行都会生成逻辑值的行向量,其大小等于数据中的行数。因此,您需要应用索引才能从集合subset = superset(subset_idx,:)中提取子集。

© www.soinside.com 2019 - 2024. All rights reserved.