0

I want to extract some certain values from a simple cell-array, which looks like:

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

And I have an additional array that tells me which element I want to extract from each Cell element. The array is as long as the cell:

ArrayExample = [2,4,...]

Basically, I want an array that says:

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

I have thought of using cellfun, but I have still some troubles using it correctly, e.g.:

cellfun(@(x) x{:}(ArrayExample),CellExample,'UniformOutput',false)
8
  • 1
    Isn't your solution(1) supposed to be 54? or am I missing something? Commented Feb 10, 2016 at 13:56
  • cellfun() already passes the content of the cell to the anonymous function, hence no need for {:} Commented Feb 10, 2016 at 13:57
  • 1
    Start with a loop, there's nothing wrong with using a loop. Have something functional first, worry about making it pretty/efficient later. Commented Feb 10, 2016 at 13:59
  • @Oleg, you're right - actually, I just found that out by using the debugger - however, I still can't pass the right values from the array Commented Feb 10, 2016 at 13:59
  • @Jonas Now it says 52, not 54... Commented Feb 10, 2016 at 14:01

1 Answer 1

4

The following

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

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

is equivalent to the loop

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

that is, cellfun() already passes the content of each cell to the anonymous function.

However, since you want to pass a numeric array as the second input to the anonymous function, and cellfun() accepts only cell() inputs, you need to use arrayfun(), which does NOT unpack cell content.

In your case:

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

and it is equivalent to:

for ii = 1:numel(Cell)
    Cell{ii}(Array(ii))
end
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for 1) helping me to understand cellfun better and 2) a simple solution that I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.