【问题标题】:Trimming vals in a matrix of arbitrary dimensions in a specified dimension修剪指定维度中任意维度的矩阵中的 val
【发布时间】:2014-07-31 12:35:46
【问题描述】:

我正在编写一个函数,该函数需要将任意维度矩阵中的某些值删除到指定维度中。

例如,假设我有一个 3x3 矩阵:

a=[1,2,3;4,5,6;7,8,9];

我可能想删除每一行中的第三个元素,在这种情况下我可以这样做

a = a(:,1:2)

但是如果 a 的维度是任意的,并且要修剪的维度被定义为函数中的参数怎么办?

使用线性索引和一些经过仔细考虑的数学是一种选择,但我想知道是否有更简洁的解决方案?

对于那些感兴趣的人,这是我当前的代码:

...
% Find length in each dimension
sz = size(dat);
% Get the proportion to trim in each dimension
k = sz(d)*abs(p);
% Get the decimal part and integer parts of k
int_part = fix(k);
dec_part = abs(k - int_part);

% Sort the array
dat = sort(dat,d);
% Trim the array in dimension d
if (int_part ~=0)
    switch d
       case 1
          dat = dat(int_part + 1 : sz(1) - int_part,:);
       case 2
          dat = dat(:,int_part + 1 : sz(2) - int_part);
    end
end
...

【问题讨论】:

  • 你不能提供一个任意尺寸的例子吗?
  • 丹,这没有意义

标签: arrays matlab matrix multidimensional-array


【解决方案1】:

没有比这更整洁的了:

function A = trim(A, n, d)
%// Remove n-th slice of A in dimension d
%// n can be vector of indices. d needs to be scalar

sub = repmat({':'}, 1, ndims(A));
sub{d} = n;
A(sub{:}) = [];

这利用了字符串 ':' 可以用作索引这一不太为人所知的事实。感谢@AndrewJanke 的this answer 和@chappjc 的bringing it to my attention

【讨论】:

    【解决方案2】:
    a = a(:, 1:end-1)
    

    end,用作矩阵索引,总是指该矩阵最后一个元素的索引

    如果你想修剪不同的维度,最简单的方法是使用 if/else 块 - 因为 MatLab 最多只支持 7 个维度,你不需要无限数量的这些来覆盖所有的基础

    【讨论】:

    • 是的,这就是我目前正在做的,但它看起来很丑:-(
    • 我认为这通常不起作用。例如,如果 A 是 2x3x4,那么您的答案会给出一个 2x11 矩阵。此外,Matlab 只允许 7 个维度是不正确的。抱歉,但投反对票
    • 我的错,这七个维度必须来自c#。期望一条线可以执行任意数量的维度有点过分?
    【解决方案3】:

    permute 函数允许置换任意维度数组的维度。 您可以将要修剪的尺寸放在规定的位置(我猜是第一个),修剪,最后恢复原始顺序。通过这种方式,您可以避免运行循环并紧凑地做您想做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多