0

I have a vector a and a second vector b to access a range of indices in a, all working as I would expect:

a=1:5400; % a==[1 2 3 4 ...] value: (1x5400 double)
b=[1 2 3]; % b value: (1x3 double)
a(b); % returns [1 2 3]

however if a b is a 2D matrix and a is matched to the size of b:

a=1:5400;
b=[1 2 3; 4 5 6; 7 8 9];
a=repmat(a,3,1); %expand matrix to match dimensions of b
c=a(b);

I get an unexpected result: c == [1 1 1;2 2 2;3 3 3] when I expected [1 2 3;4 5 6;7 8 9]

Can somebody offer an explanation?

user2305193
  • 2,079
  • 18
  • 39
  • Yes, if `b(1)=324`, then indeed `c(1)=324` should be true as well. Reposting with a simpler example is not necessary in my opinion, you can verify this easily enough using this example, or, for clarity, use `a=1:10` or something and verify that indeed this is what's going on. I quickly checked with `a=1:10;b=randi(10,5,1);c=a(b)` and indeed `c==b` is true. What *does* happen is that `c` will be a row vector, so actually `c.'==b`, i.e. the transpose of `c` is equal to `b`. It even works for me with your numbers. – Adriaan Feb 25 '17 at 11:46
  • I just stumbled upon the solution which is trivial: `repmat(a,3,1);` is not necessary, then everything works as expected. If you reopen I'll post it as solution. – user2305193 Feb 25 '17 at 12:33
  • 2
    @user2305193 The issue is that linear indexing goes down the columns. When you call `repmat`, you are repeating a *row vector* three times and stacking them on top of one another. Since you are accessing the first 9 elements of this new "duplicated" matrix, it will go down the columns so it grabs the columns of 1's, 2's, and 3's. When you remove the `repmat` it is correct. The result of indexing with a linear array of indices will always be the same shape of the array of indices and the *shape* of the array of indices and the initial matrix do not need to correspond. – Suever Feb 25 '17 at 14:17
  • thanks again @Suever, cleaned up unnecessary comments for others to follow up on – user2305193 Feb 26 '17 at 12:21

0 Answers0