Given a cell array of [R G B]
values in MATLAB
, I need to find sub-cell_array consisting of those particular elements which satisfy a condition. (using a cell function).
I was thinking like:
subset = cellfun(@(x) condition(x), superset, 'UniformOutput',false);
But this gives 1 for those elements which satisfy the condition and 0 otherwise, as expected. But I need a subset, consisting of those elements for which condition == 1
.
Please suggest.
% 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);
An alternative that let you avoid cycling over each cell array element:
% 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,:);
No matter what approach you prefer, applying a condition to each row of your data produces a row vector of logical values whose size is equal to the number of rows in your data. Hence, you need to apply indexing in order to extract a subset from your set subset = superset(subset_idx,:)
.