How to refer a high dimension matrix

I have a high dimensional matrix A, two row vectors ind1 and ind2. The length of ind1 and ind2 is flexible but
length(size(A))==length(ind1)+length(ind2)
is always true. So how can I refer to the element of A whose index is (ind1(1),...ind1(end),ind2(1),...ind2(end))? Since the length of ind1 and ind2 is flexible, I couldn't simply write out every index.

 Accepted Answer

Stephen23
Stephen23 on 7 Jul 2015
Edited: Stephen23 on 7 Jul 2015
This is exactly what sub2ind is for, it generates the linear indices corresponding to subscript indices. Try doing something like this (untested):
ids = num2cell([ind1,ind2]);
idx = sub2ind(size(A),ids{:});
A(idx) % access that element

3 Comments

It works perfectly! Thank you so much!
ids{:}
is the trick I was not aware of. Actually
ids = num2cell([ind1,ind2]);
A(ids{:})
will also refer to the same element. I don't know how A(ids{:}) works while A(ids) won't. This is interesting.
James Tursa
James Tursa on 7 Jul 2015
Edited: James Tursa on 7 Jul 2015
ids is a cell array, but ids{:} is a comma separated list. E.g., see this link:
I see. ids{:} is equivalent to typing out every element of it explicitly,
ids{1},ids{2},ids{3},....ids{end}
which is exactly the index for reference!

Sign in to comment.

More Answers (0)

Asked:

on 7 Jul 2015

Edited:

on 8 Jul 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!