Alexey Alexandrov
Alexey Alexandrov

Reputation: 3129

Octave: apply given mapping to cell array

Imagine I have a cell array "list of lists" in Octave:

octave:6> a = {[1], [3,4], [5,6,7], [8,9,10,11]}
a =
{
  [1,1] =  1
  [1,2] =

     3   4

  [1,3] =

     5   6   7

  [1,4] =

      8    9   10   11

}

Now I want to extract a given element from each of the nested rows and the index of each of them is given in a list. E.g. [1, 2, 2, 3] would mean return [1, 4, 6, 10].

What is the best Octave-ish way to do this? I know how to do that with a loop, but that seems ugly...

Upvotes: 3

Views: 194

Answers (1)

Alexey Alexandrov
Alexey Alexandrov

Reputation: 3129

It seems I have found the solution that is good to me. I realized that cellfun() takes a number of arguments so I can perform the element-wise mapping easily.

octave:31> cellfun(@(x,y) x(y), a, {1,2,2,3})
ans =

    1    4    6   10

Upvotes: 2

Related Questions