将Matlab矩阵转换为向量 [英] Converting a matlab matrix to a vector
问题描述
我想在预定义的位置获取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,j
相对应的位置为我提供A
的值.我尝试过
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
这是什么matlab语法?请避免建议循环或非矢量化形式的任何东西,因为我需要快速完成此工作.希望会有一些内置功能.
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.
推荐答案
以最快的方式获取它,请使用线性索引:
to get it in the fastest way, use linear indexing:
A((j-1)*size(A,1)+i)
请记住,MATLAB使用列优先顺序.
remember that MATLAB uses a column-major order.
这篇关于将Matlab矩阵转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!