2

In MATLAB, have an N-dimensional cell C, where N is an integer only determined at runtime. How do I access a specific element of C with a vector variable id? For example, with N=3 and id=[1,5,2], how to programmatically get the content of c{1,5,2}? I cannot hard-code it as c{id(1),id(2),id(3)} since N is only fixed at runtime.

6
  • Does c{id} not work? Commented Jan 11, 2016 at 9:43
  • 1
    @thewaywewalk no, c{id} returns c{id(1)}, c{id(2)},..., c{(id(N))} Commented Jan 11, 2016 at 9:44
  • well, C{[id(1),id(2),id(3)]} and C{id} are equivalent. Commented Jan 11, 2016 at 9:52
  • @thewaywewalk ...but very different from c{id(1),id(2),id(3)} Commented Jan 11, 2016 at 10:56
  • @Dan ... which for the input I Imagined is not working at all, the same stands for your answer. For me the question is totally unclear. But your mentalist skills seemed good enough and the OP is satisfied. So why not... Commented Jan 11, 2016 at 11:02

1 Answer 1

2

If id is a cell array, then you can use sub2ind for this by taking advantage of the comma separated list syntax ,i.e. {:}, to send a variable number of inputs to sub2ind

id = {1,5,2};
ind = sub2ind(size(C), id{:})
c{ind}

if id isn't a cell array (and for some reason can't be created as one), then use num2cell to convert it.

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.