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
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:
Works just like
setdiff
really, but builds a logical mask instead of a list of explicit indices.Very easy:
This works even if
k
is the first or last element.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 usevector(k)=[];
Another alternative without
setdiff
() isJust for fun, here's an interesting way with
setdiff
:What's interesting about this, besides the use of
setdiff
, you ask? Look at the placement ofend
. MATLAB'send
keyword translates to the last index ofvector
in this context, even as an argument to a function call rather than directly used withparen
(vector
's()
operator). No need to usenumel(vector)
. Put another way,That is not completely obvious IMO, but it can come in handy in many situations, so I thought I would point this out.