关于n维度矩阵的Matlab最后维度访问

时间:2013-11-13 13:56:24

标签: arrays matlab multidimensional-array

我输入的矩阵可以包含多个维度:n × mn × m × pn × m × p × q或...

我想要做的是访问最后一个维度,例如:

data = input(:,:,1)

问题是:的数量可能会发生变化。

6 个答案:

答案 0 :(得分:11)

你应该利用这样一个事实,即数组中的索引可以是包含':'的字符串:

>> data = rand(2, 2, 2, 5);
>> otherdims = repmat({':'},1,ndims(data)-1);
>> data(otherdims{:}, 1)
ans(:,:,1) =
    7.819319665880019e-001    2.940663337586285e-001
    1.006063223624215e-001    2.373730197055792e-001
ans(:,:,2) =
    5.308722570279284e-001    4.053154198805913e-001
    9.149873133941222e-002    1.048462471157565e-001

有关详细信息,请参阅the documentation on subsref

答案 1 :(得分:5)

这有点像黑客攻击,但是你可以这样做:

data = rand(2,2,3);

eval(['data(' repmat(':,',1,ndims(data)-1) '1)'])

这将给出(取决于randon数字):

ans =

      0.19255      0.56236
      0.62524      0.90487

答案 2 :(得分:2)

您可以使用shiftdim将最后一个维度带到第一个维度并将其编入索引并将其重新整形

x = rand(2,3,4,5,6);

sz = size(x);
A = shiftdim(x, numel(sz)-1);
B = reshape(A(1,:), sz(1:end-1));

>> isequal(B, x(:,:,:,:,1))
ans =
     1

或者您可以使用subsref对其进行索引:

B = subsref(x, substruct('()', [num2cell(repmat(':', 1, ndims(x)-1)) 1]))

答案 3 :(得分:2)

好问题!

另一种可能性是在块中使用线性索引,然后重塑:

x = rand(2,3,4,5); % example data
n = 2; % we want x(:,:,...,:,n)

siz = size(x);
b = numel(x)/siz(end); % block size
result = reshape(x(b*(n-1)+1:b*n),siz(1:end-1));

这似乎是我电脑中最快的方法(但要自己尝试;这可能取决于Matlab版本和系统)

答案 4 :(得分:1)

我认为这样做:

a = rand(2,2,2,3)

s = size(a)
r = reshape(a, [], s(end))
reshape(r(:,1), s(1:end-1)) %// reshape(r(:,2), s(1:end-1)) gives you a(:,:,:,...,2) etc...

我对Dennis的(正确)答案进行了基准测试,结果相同,但不需要eval,如果可能的话,总是值得避免。

答案 5 :(得分:0)

以防GNU Octave读者到达此处。

@Rody Oldenhuis的回答可以写成Octave中的单行:

> data = reshape(1:8, 2, 2, 2);
> data({':'}(ones(1,ndims(data)-1)){:}, 1)
ans =

   1   3
   2   4

下面:

{':'}(ones(1,ndims(data)-1)){:}

表示:

tmp = {':'};
tmp = tmp(ones(1,ndims(data)-1));
tmp{:}

当然,repmat({':'},1,ndims(data)-1){:}也有效。