Indexing arrays with matrices

3 views (last 30 days)
Andrew Newell
Andrew Newell on 31 Mar 2011
Matt's recent Hump-day challenger has led me ponder a strange form of indexing used in repmat. Consider a 3d array like the following:
A = reshape(1:8,[2 2 2])
A(:,:,1) =
1 3
2 4
A(:,:,2) =
5 7
6 8
Now run repmat and stop at the second last line:
B = A(subs{:});
Putting in the values for subs, this is the same as
B = A([1 1; 2 2],[1; 2],[1 1; 2 2]);
How is MATLAB interpreting indexing like this?

Accepted Answer

Matt Fig
Matt Fig on 31 Mar 2011
Now that is the kind of wondering that lead me to the project which lead me to the challenger!
I think we can see what is going on by taking it one at a time:
A([1 1; 2 2],:,:)
So this produces the same thing as this:
A([1 2 1 2],:,:) % Read the indexing array as (:).
Now it makes sense: Take - Row one, then Row two, then Row one, then Row two for all higher dimensions (i.e., for each column and page).
Similarly with the other indexing arrays.
REPMAT and BSXFUN are deep funtions in terms of really understanding how they (and consequently, MATLAB indexing in general) work.
  1 Comment
Andrew Newell
Andrew Newell on 31 Mar 2011
I see the light! Just to add to this explanation, if you do the following series of commands
B = A([1 2 1 2],:,:);
C = B(:,[1; 2],:);
D = C(:,:,[1 2 1 2]);
you get the same as
E = A(subs{:});
isequal(D,E)
ans =
1
Thank you!

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!