0

I need help solving an indexing problem. The assigned problem states: Two matrices (x and y) give the coordinates to form matrix B from matrix A. Produce the matrix B which contains the values of A at the given coordinates in x and y. For instance:

x = [1 1 1; 2 2 1]
y = [1 2 1; 3 2 4]
%This would read as (1,1),(1,2),(1,1),(2,3),(2,2),(1,4)
% Given matrix: 
A = [6 7 8 9; 10 11 12 13];
%This would give us this answer for B (using the coordinate scheme above): 
B=[6 7 6; 12 11 9];

I'm guessing I need to use the find function in conjunction with a sub2ind function, but I'm not 100% sure how to translate that into working code. The only thing I can think of would be to do something like this:

B=((x(1),(y(1)), (x(2),y(2)).......

But that would only work for the defined matrix above, not a randomly generated matrix. I tried looking for a similar problem on the site, but I couldn't find one. Your help would be really appreciated!

  • Try using a loop. Sometimes the simplest approach is the best. – Andrey Rubshtein Jul 07 '13 at 20:32
  • 2
    You're right, `sub2ind` would be helpful here, as well `reshape` if you like. You don't need a loop -this can be done on one line. Read about [linear indexing here](http://www.mathworks.com/help/matlab/math/matrix-indexing.html#f1-85511) to see if you can figure out what to do wit the output from `ind2sub`. – horchler Jul 07 '13 at 21:05
  • This has been answered in many questions, _e.g_: [Selecting elements from an array in MATLAB](http://stackoverflow.com/questions/13023997/), [Changing multiple elements (of known coordinates) of a matrix without a for loop](http://stackoverflow.com/questions/12294232), [MATLAB sub2ind using vectors](http://stackoverflow.com/questions/16530668), and many more... – Eitan T Jul 08 '13 at 12:45
  • possible duplicate of [MATLAB sub2ind using vectors](http://stackoverflow.com/questions/16530668/matlab-sub2ind-using-vectors) – bla Jul 11 '13 at 23:57

1 Answers1

1

You can't do it for randomly generated matrices, because you have to ensure that matrix A has lines and columns as required from the values of x and y.

In this case, you can write:

for i=1:length(x(:))
   B(i)=A(x(i),y(i));
end
B=reshape(B,size(x));
Adiel
  • 3,071
  • 15
  • 21
  • I keep getting an error when I implement your code: "To RESHAPE the number of elements must not change." and "Error in B=reshape(B,size(x)) ". Here is what I put in the script, it isn't working:x = [1 1 1; 2 2 1] y = [1 2 1; 3 2 4] A = [6 7 8 9; 10 11 12 13] for i=1:length(x(:)) B(i)=A(x(i),y(i)); end B=reshape(B,size(x)) – John Wayne's Stunt Double Jul 07 '13 at 20:53
  • I copied your code, and get B=[6 7 6; 12 11 9]. I don't know what the problem... what do you get for `size(B)`? – Adiel Jul 07 '13 at 21:00
  • I'm sorry, I just retried after clearing `clear,clc` the command window, and it worked! I got the correct matrix. Thank you for your assistance! :D – John Wayne's Stunt Double Jul 07 '13 at 21:12