Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我有一个可变维度矩阵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一半大小的向量。然后,单元格数组的内容作为逗号分隔的列表输出(使用{:}语法),并用作x的索引。之所以可行,是因为在索引语句中使用':'和:的方式相同(即“该维的所有元素”)。 更多&回答... |
![]() |
![]() |