1

How can one access multiple elements in a cell array of vectors or matrices? For instance, suppose one has the following cell array:

c={[1 2 3] [4 5 6 7]};

One can access elements 2, 6, and 7 as follows:

[c{1}(2) c{2}(3) c{2}(4)]

Suppose one instead has two vectors with indexes to the desired elements, the first vector of which contains the cell index and the second of which contains the vector index of the desired elements.

For instance, to access the above three elements, one might want to use the "cell index vector" ci=[1 2 2] and the "vector index vector" vi=[2 3 4] in some manner akin to the following:

c{ci}(vi)

How can one perform such a nested access without resorting to loops?

1 Answer 1

1

I don't think what you want can be done, and here's why I think this: consider arrays. You can have an array c=rand(3), which is 3x3. You can access it as c(1:2,3) to select a subarray, but you can't access the (1,1), the (2,2) and the (3,3) element at the same time using array indices. You can use linear indices for arrays, as in c(sub2ind([3,3],[1 2 3],[1 2 3])). But for cells the two kinds of indices are distinctly different, and you can't use a linear kind of indexing which mixes the cell and the array indices.

Here's an even better argument. Cells are very slow, so their strong side must be something else. And that's their versatility: you can put anything into a cell. Including function handles:

c={1, [2 3], @sin};

But then something funny happens if you try to index:

>> c{2}(2)

ans =

     3

>> c{3}(2)

ans =

    0.9093

This is probably inconclusive, but to me this very strongly suggests that you can't treat cell indices universally, on an equal footing; any indexing has to be specific to the given element of your cell (depending on whether it's a scalar, an array, a function handle, or a giraffe).

Sign up to request clarification or add additional context in comments.

Comments

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.