我有一个可变维度矩阵,X.我想要一个能在一个维度上得到X的前半部分的函数.IE,我想要这样的东西:
function x = variableSubmatrix(x, d)
if d == 1
switch ndims(x)
case 1
x = x(1:end/2);
case 2
x = x(1:end/2, :);
case 3
x = x(1:end/2, :, :);
(...)
end
elseif d == 2
switch ndims(x)
case 2
x = x(:, 1:end/2);
case 3
x = x(:, 1:end/2, :);
(...)
end
elseif (...)
end
end
Run Code Online (Sandbox Code Playgroud)
我不太清楚如何做到这一点.我需要快速,因为这将在计算中多次使用.
这应该做的伎俩:
function x = variableSubmatrix(x, d)
index = repmat({':'},1,ndims(x)); %# Create a 1-by-ndims(x) cell array
%# containing ':' in each cell
index{d} = 1:size(x,d)/2; %# Create an index for dimension d
x = x(index{:}); %# Index with a comma separated list
end
Run Code Online (Sandbox Code Playgroud)
以上首先在每个单元格中创建一个逐个单元ndims(x)格的阵列':'.然后将对应于维度的单元格d替换为包含数字1到维度大小一半的向量d.然后,将单元格数组的内容输出为逗号分隔列表(使用{:}语法)并用作索引x.这是有效的,因为在索引语句中使用时':',:它们的处理方式相同(即"此维度的所有元素").