如何查找单元格中最大N元素的索引?

时间:2015-02-08 18:03:47

标签: matlab cells

我是Matlab,我知道我可以使用它来获得最大数量的单元格。

cell_max = cellfun(@(x) max(x(:)), the_cell);

然而,这有两个问题。首先,我还需要最大值的索引。其次,我不需要每个单元格的单个最大值,而是N个最大值。

Matlab中的单元格可以实现吗?

更新:我有一个像素矩阵,我通过在某个输入图像文件上运行过滤器获得。然后,我从该矩阵中将此矩阵拆分为切片,并希望每个切片仅保留N个最大值,而所有其他条目应设置为零。 (所以我最后不需要索引,但是它们允许我创建一个新的空单元格并复制大值。)

Tiles = mat2tiles(FilterResult, tileSize, tileSize);

如果我的用例更简单,那么使用mat2tiles script,我很高兴知道。

1 个答案:

答案 0 :(得分:2)

例程cellfun可以返回您传入的函数的多个参数(请参阅文档)。因此,假设每个单元格包含值的数值向量,您可以像这样获取每个单元格的N个最大元素:

% Using random data for the_cell    
the_cell{1, 1} = rand(1, 12);
the_cell{1, 2} = rand(1, 42);
the_cell{2, 1} = rand(1, 18);
the_cell{2, 2} = rand(1, 67);

% First sort elements in each cell in descending order and keep indices
[s, i] = cellfun(@(x)sort(x(:), 'descend'), the_cell, 'UniformOutput', false);

% Then, in each resulting `s` and `i` cell arrays, 
% take only the `N` first elements and indices
N = 4;
NLargestValues = cellfun(@(x)x(1:N), s, 'UniformOutput', false);
NLargestIndices = cellfun(@(x)x(1:N), i, 'UniformOutput', false);

注意:UniformOutput设置为false,因为输出不是标量。

<强>更新

根据您的更新和评论,您可以将所有操作放在tileOperations函数中:

% Operation to perform for each tile in the_cell array
function [tile] = tileOperations(tile, N) 
%[
    % Return unique sorted values of the tile
    v = unique(tile(:));

    % Find threshold index
    i = length(v) - N;
    if (i <= 1), return; end % Quick exit if not enough elements 

    % Set elements below threshold to zero
    threshold = v(i);
    tile(tile < threshold) = 0.0;    
%]
end

然后,您只需拨打cellfun一次即可对the_cell中的所有图块重复执行操作:

filteredTiles = cellfun(@(x)tileOperations(x), the_cell, 'UniformOutput', false);
相关问题