Getting corresponding coordinates of a vectorized matrix

Viewed 61

I have a matrix X of size n x m. I resized X to a vector a of length n x m.

How can I know "automatically" that the ith element in vector a corresponds to what element position (coordinates) in X?

I have written the following MATLAB code but I do not know how to continue.

X = rand(10,10);
[n,m] = size(X);
a = reshape(X, [n*m, 1]);
t = zeros(length(a),1);

for i = 1 : length(a)
    t(i) = % I want to perform here the sum over the x and y coordinate values of the element in X 
             % that corresponds to the ith element in vector a.
end

Any help will be very appreciated.

1 Answers

That's what ind2sub does:

[row, col] = ind2sub([m n], i);

However, you may prefer to do it manually:

row = mod(i-1,m)+1;
col = floor((i-1)/m)+1;

This works because Matlab used column-major order for storing array elements. For example, in a 3×4 matrix the order in which the elements are stored in memory is as follows:

 1     4     7    10
 2     5     8    11
 3     6     9    12

So the entry in the 2nd row, 3rd column is the 8th element in (column-major) linear order. When this matrix is reshaped into a vector (or into any other shape) this linear order is preserved. Therefore you can retrieve the original coordinates by divisions and modulus operations. Note also that, since Matlab's indexing is 1-based (as opposed to 0-based), the modulus operations need to be shifted by 1.

Related