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

Extract specific values from cell based on array in MATLAB

我想从一个简单的 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)

以下

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()已经将每个单元格的内容传递给了匿名函数。

但是,由于您想将 numeric 数组作为第二个输入传递给匿名函数,而 cellfun() 仅接受 cell() 输入,您需要使用 arrayfun(),它不会解压单元格内容。

你的情况:

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

相当于:

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