Extract every element except every n-th element of vector

巧了我就是萌 提交于 2020-01-13 08:39:25

问题


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.


回答1:


You can eliminate elements like this:

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



回答2:


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 ...]



回答3:


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



回答4:


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 ...]



回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/13469718/extract-every-element-except-every-n-th-element-of-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!