将 matlab 矩阵转换为向量
我想在预定义位置获取 Matlab 矩阵的元素向量。例如,我有以下内容,
>> i = [1,2,3];
>> j = [1,3,4];
>> A = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16]
A =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
我想要一个向量,该向量将为我提供与 i,j
对应的位置处的 A
值。我尝试过
A(i,j)
ans =
1 3 4
5 7 8
9 11 12
,但这不是我想要的。我想得到以下
>> [A(i(1),j(1)); A(i(2),j(2));A(i(3),j(3))]
ans =
1
7
12
内容 matlab 语法是什么?请避免建议循环或任何非矢量化形式的内容,因为我需要快速完成此操作。希望会有一些内置功能。
I want to get a vector of elements of a Matlab matrix at predefined locations. For example, I have the following
>> i = [1,2,3];
>> j = [1,3,4];
>> A = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16]
A =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
I want a vector that will give me the values of A
at the locations correspongin to i,j
. I tried
A(i,j)
ans =
1 3 4
5 7 8
9 11 12
but this is not what I wanted. I want to get the following
>> [A(i(1),j(1)); A(i(2),j(2));A(i(3),j(3))]
ans =
1
7
12
What is the matlab syntax for that? Please, avoid suggesting for loops or anything that is not in a vectorized form, as I need this to be done fast. Hopefully there will be some built-in function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要以最快的方式获取它,请使用线性索引:
请记住 MATLAB 使用列优先顺序。
to get it in the fastest way, use linear indexing:
remember that MATLAB uses a column-major order.
如果您确实渴望速度,您可以尝试制作自己的 sub2ind.m 副本,以删除该函数所做的所有输入检查。
If you really crave speed, you might try making your own copy of sub2ind.m that strips out all the input-checking that that function does.
要了解如何执行此操作,最好了解 matlab 如何存储其数组。在矩阵中:
matlab 存储沿列向下的元素。因此它们实际上按顺序驻留在内存中:
您实际上可以使用 SINGLE 索引来索引二维数组。这就是 sub2ind 技巧起作用的原因。由于您想要获取的元素是按列排序存储的第 1 个、第 10 个和第 15 个元素,
要确认 sub2ind 给出了该索引列表,请尝试...
To understand how to do this, it is best to understand how matlab stores its arrays. In the matrix:
matlab stores the elements going DOWN the columns. So they actually reside in memory in the order:
You can actually index a 2-d array using a SINGLE index. This is why the sub2ind trick works. Since the elements that you want to get are the 1st, 10th and 15th elements, as stored in a column-wise ordering,
To confirm that sub2ind gave that index list, try it...
现在我正在使用这个:
For now I'm using this: