从另一个数组的索引中获取数组的值:Matlab [英] Get the values of an array from indices in another array: Matlab
问题描述
我有一个20x1的双精度数组A
和一个1000x1的双精度数组B
.
I have a 20x1 double array A
, and a 1000x1 double array B
.
我想获取数组C
,其中数组C
将是1000x1的两倍,其中B
中的值用于索引A
中的值,如下所示:
I want to get array C
, where array C
will be 1000x1 double where the values in B
are used to index the values in A
like so:
C(1) = A(B(1))
C(2) = A(B(2))
...
C(i) = A(B(i))
...
c(1000) = A(B(1000))
这怎么办?
推荐答案
您不需要为此循环,可以直接使用:
You don't need a loop for this, you can directly use:
C = A(B)
这利用了MATLAB的矩阵索引,这是使用数组而不是整数时在MATLAB中处理索引的方式.
This takes advantage of MATLAB's matrix indexing, which is the way indexing is handled in MATLAB when an array is used instead of an integer.
看一下文档: https://uk. mathworks.com/help/matlab/math/matrix-indexing.html
例如:
A = [11 12 13];
B = [1 2 3 1 2 3 3 2 1];
C = A(B)
C =
11 12 13 11 12 13 13 12 11
确保B仅包含作为A的有效索引的整数(不少于1或大于A的长度).
Ensure that B only contains integers which are valid indices of A (not less than 1 or greater than the length of A).
这篇关于从另一个数组的索引中获取数组的值:Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!