8
votes

Given a vector

A = [1,2,3,...,100]

I want to extract all elements, except every n-th. So, for n=5, my output should be

B = [1,2,3,4,6,7,8,9,11,...]

I know that you can access every n-th element by

A(5:5:end)

but I need something like the inverse command. If this doesn't exist I would iterate over the elements and skip every n-th entry, but that would be the dirty way.

6
read my answer, the "inverse command" you look for exists. Logical indexing is an important part of Matlab, and a very important feature to know and use. - Castilho
given the help of all of you, I guess this is even more what i was looking for: A(mod(1:100,5)~=0) thanks! - Thomas

6 Answers

13
votes

You can eliminate elements like this:

A = 1:100;
removalList = 1:5:100;
A(removalList) = [];
4
votes

Use a mask. Let's say you have

A = 1 : 100;

Then

m = mod(0 : length(A) - 1, 5);

will be a vector of the same length as A containing the repeated sequence 0 1 2 3 4. You want everything from A except the elements where m == 4, i.e.

B = A(m ~= 4);

will result in

B == [1 2 3 4 6 7 8 9 11 12 13 14 16 ...]
2
votes

Or you can use logical indexing:

n = 5; % remove the fifth
idx = logical(zeroes(size(A))); % creates a blank mask
idx(n) = 1; % makes the nth element 1
A(idx) = []; % ta-da!

About the "inversion" command you cited, it is possible to achieve that behavior using logical indexing. You can negate the vector to transform every 1 in 0, and vice-versa.

So, this code will remove any BUT the fifth element:

negatedIdx = ~idx;
A(negatedIdx) = [];
1
votes

why not use it like this?

say A is your vector

A = 1:100
n = 5
B = A([1:n-1,n+1:end])

then

B=[1 2 3 4 6 7 8 9 10 ...]
0
votes

One possible solution for your problem is the function setdiff().

In your specific case, the solution would be:

lenA = length(A);
index = setdiff(1:lenA,n:n:lenA);
B = A(index)

If you do it all at once, you can avoid both extra variables:

B = A( setdiff(1:end,n:n:end) )

However, Logical Indexing is a faster option, as tested:

lenA = length(A);
index = true(1, lenA);
index(n:n:lenA) = false;
B = A(index)

All these codes assume that you have specified the variable n, and can adapt to a different value.

0
votes

For the shortest amount of code, you were nearly there all ready. If you want to adjust your existing array use:

A(n:n:end)=[];

Or if you want a new array called B:

B=A;
B(n:n:end)=[];