Select all elements except one in a vector

2020-07-02 11:39发布

My question is very similar to this one but I can't manage exactly how to apply that answer to my problem.

I am looping through a vector with a variable k and want to select the whole vector except the single value at index k.

Any idea?

for k = 1:length(vector)

   newVector = vector( exluding index k);    <---- what mask should I use? 
   % other operations to do with the newVector

end

6条回答
ゆ 、 Hurt°
2楼-- · 2020-07-02 11:43

Another way you can do this which allows you to exclude multiple indices at once (or a single index... basically it's robust to allow either) is:

newVector = oldVector(~ismember(1:end,k))

Works just like setdiff really, but builds a logical mask instead of a list of explicit indices.

查看更多
倾城 Initia
3楼-- · 2020-07-02 11:44

Very easy:

newVector = vector([1:k-1 k+1:end]);

This works even if k is the first or last element.

查看更多
神经病院院长
4楼-- · 2020-07-02 11:49

vector([1:k-1 k+1:end]) will do. Depending on the other operations, there may be a better way to handle this, though.

For completeness, if you want to remove one element, you do not need to go the vector = vector([1:k-1 k+1:end]) route, you can use vector(k)=[];

查看更多
爷的心禁止访问
5楼-- · 2020-07-02 12:02

Another alternative without setdiff() is

vector(1:end ~= k)
查看更多
祖国的老花朵
6楼-- · 2020-07-02 12:02

Just for fun, here's an interesting way with setdiff:

vector(setdiff(1:end,k))

What's interesting about this, besides the use of setdiff, you ask? Look at the placement of end. MATLAB's end keyword translates to the last index of vector in this context, even as an argument to a function call rather than directly used with paren (vector's () operator). No need to use numel(vector). Put another way,

>> vector=1:10;
>> k=6;
>> vector(setdiff(1:end,k))
ans =
     1     2     3     4     5     7     8     9    10
>> setdiff(1:end,k)
Error using setdiff (line 81)
Not enough input arguments.

That is not completely obvious IMO, but it can come in handy in many situations, so I thought I would point this out.

查看更多
【Aperson】
7楼-- · 2020-07-02 12:03
%create a logic vector of same size:
l=ones(size(vector))==1;
l(k)=false;
vector(l);
查看更多
登录 后发表回答