登录论坛

查看完整版本 : 可变尺寸的MATLAB子矩阵


poster
2019-12-10, 20:41
我有一个可变维度矩阵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 我不太确定该怎么做。我需要它快,因为它将在计算中多次使用。



回答:

这应该可以解决问题:

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 上面的代码首先创建一个1- ndims(x)单元格数组,每个单元格中均带有':' 。然后,将对应于维d的像元替换为一个包含数字1到维d一半大小的向量。然后,单元格数组的内容作为逗号分隔的列表 (http://www.mathworks.co.uk/access/helpdesk/help/techdoc/matlab_prog/br2js35-1.html)输出(使用{:}语法),并用作x的索引。之所以可行,是因为在索引语句中使用':'和:的方式相同(即“该维的所有元素”)。



更多&回答... (https://stackoverflow.com/questions/2931550)