Select all elements except one in a vector
Another alternative without setdiff
() is
vector(1:end ~= k)
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)=[];
Very easy:
newVector = vector([1:k-1 k+1:end]);
This works even if k
is the first or last element.
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.