2

I'm writing a function that requires some values in a matrix of arbitrary dimansions to be dropped in a specified dimension.

For example, say I have a 3x3 matrix:

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

I might want to drop the third element in each row, in which case I could do

a = a(:,1:2)

But what if the dimensions of a are arbitrary, and the dimension to trim is defined as an argument in the function?

Using linear indexing, and some carefully considered maths is an option but I was wondering if there is a neater soltion?

For those interested, this is my current code:

...
% 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
...
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
SmallJoeMan
  • 353
  • 4
  • 9

3 Answers3

1

It doesn't get any neater than this:

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{:}) = [];

This makes use of the not very well known fact that the string ':' can be used as an index. With due credit to this answer by @AndrewJanke, and to @chappjc for bringing it to my attention.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0
a = a(:, 1:end-1)

end, used as a matrix index, always refers to the index of the last element of that matrix

if you want to trim different dimensions, the simplest way is using and if/else block - as MatLab only supports 7 dimensions at most, you wont need an infinite number of these to cover all bases

Mauvai
  • 461
  • 2
  • 5
  • 17
  • Yeah that's what I'm currently doing, but it looks pretty ugly :-( – SmallJoeMan Jul 31 '14 at 13:03
  • I dont think this works in general. For example, if A is 2x3x4, your answer gives a 2x11 matrix. Also, it's not true that Matlab only allows 7 dimensions. Sorry, but downvoting – Luis Mendo Jul 31 '14 at 15:19
  • My bad, the seven dimensions must be from c#. Its a bit much to expect one line that does any arbitrary number of dimensions? – Mauvai Jul 31 '14 at 15:43
0

The permute function allows to permute the dimension of an array of any dimension. You can place the dimension you want to trim in a prescribed position (the first, I guess), trim, and finally restore the original ordering. In this way you can avoid running loops and do what you want compactly.

Emerald Weapon
  • 2,392
  • 18
  • 29