Matlab-访问多维数组的一部分 [英] Matlab - Accessing a part of a multidimensional array
问题描述
我正在尝试访问Matlab中多维数组的一部分-可以这样完成:X(2:3, 1:20, 5, 4:7)
但是,元素的数量和范围都不是固定的,因此我想提供数组的索引-对于上面的示例,它们应该是
I'm trying to access a part of a multidimensional array in Matlab - it could be done like this: X(2:3, 1:20, 5, 4:7)
However, neither the number of elements, nor the ranges are fixed, so I want to provide the indices from arrays - for the above example they'd be
ind1 = [2 1 5 4];
ind2 = [3 20 5 7];
对于固定数量的尺寸,这不是问题(X(ind1(1):ind2(1),...)
,但是由于不是这样,所以我不确定如何在Matlab中实现此方法.有没有办法?还是应该以不同的方式来对待?
For a fixed number of dimensions this is not a problem (X(ind1(1):ind2(1),...)
, but since they are not I'm not sure how to implement this in Matlab. Is there a way? Or should I approach this differently?
推荐答案
Using comma separated lists you can make it a more quick and friendly:
% some test data
ind1 = [2 1 5 4];
ind2 = [3 20 5 7];
X = randi(99,20,20,20,20);
% get all subscripts in column format
vecs = arrayfun(@colon,ind1,ind2,'un',0);
% extract the values
result = X(vecs{:});
这篇关于Matlab-访问多维数组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!