在MATLAB中基于数组从单元格中提取特定值

时间:2016-02-10 13:50:47

标签: arrays matlab cell-array

我想从一个简单的cell-array中提取某些值,如下所示:

CellExample{1} = [1,54,2,3,4]
CellExample{2} = [1,4,1,92,9,0,2]
...

我有一个额外的数组告诉我要从每个Cell元素中提取哪个元素。该数组与单元格一样长:

ArrayExample = [2,4,...]

基本上,我想要一个数组说:

Solution(1) = CellExample{1}(ArrayExample(1)) = 54
Solution(2) = CellExample{2}(ArrayExample(2)) = 92

我曾想过使用cellfun,但我仍然有一些麻烦正确地使用它,例如:

cellfun(@(x) x{:}(ArrayExample),CellExample,'UniformOutput',false)

1 个答案:

答案 0 :(得分:4)

以下

Cell{1} = [1,54,2,3,4]
Cell{2} = [1,4,1,92,9,0,2]

cellfun(@(x) disp(x), Cell)

相当于循环

for ii = 1:numel(Cell)
    disp(Cell{ii})
end

也就是说,cellfun()已将每个单元格的内容传递给匿名函数。

但是,由于您希望将数字数组作为匿名函数的第二个输入传递,并且cellfun()仅接受cell()个输入,因此您需要使用 arrayfun() ,它不解包单元格内容。

在你的情况下:

arrayfun(@(c,pos) c{1}(pos), Cell, Array)

它相当于:

for ii = 1:numel(Cell)
    Cell{ii}(Array(ii))
end