获取向量化矩阵的相应坐标 [英] Getting corresponding coordinates of a vectorized matrix

查看:61
本文介绍了获取向量化矩阵的相应坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为 n x m 的矩阵 X .我将 X 的大小调整为长度为 n x m 的向量 a .

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

我如何自动"知道向量 a 中的 ith 元素与 X 中的元素位置(坐标)相对应?

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

我已经编写了以下MATLAB代码,但我不知道如何继续.

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

任何帮助将不胜感激.

推荐答案

这就是 ind2sub 可以:

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;

这行得通,因为Matlab使用了列大顺序,用于存储数组元素.例如,在3×4矩阵中,元素在内存中的存储顺序如下:

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

因此,第二行第三列中的条目是(主列)线性顺序的第8个元素.当将此矩阵重塑为矢量(或其他任何形状)时,将保留此线性顺序.因此,您可以通过除法和模运算来检索原始坐标.还要注意,由于Matlab的索引是基于1的(而不是基于0的),所以模数运算需要移位1.

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.

这篇关于获取向量化矩阵的相应坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆