Getting the index of a vector element with a given value?
Ben Abbott
bpabbott at mac.com
Fri Jul 18 05:55:47 CDT 2008
On Jul 18, 2008, at 5:24 AM, Primoz PETERLIN wrote:
> Hello again,
>
> Another question. Suppose I have a vector of values, and would want to
> know the indices of the elements of this vector have a given value.
> What is the easiest way to get them? I came up with the following:
>
> function indices = vindex(vec, value)
> indices = [];
> for i = 1:length(vec)
> if (vec(i) == value)
> indices = [indices, i];
> endif
> endfor
> if (length(indices) == 0)
> indices = 0;
> endif
> endfunction
>
> Does anything more general and faster exist already? I am aware of
> find(), which returns the indices of nonzero elements, and index(),
> which performs a similar task on strings (although the latter only
> returns the index of the first element).
>
> TIA, Primož
I don't know what you're intending to do with those indices, but If
you wish to do something special to the values that qualify ...
perhaps set them equal to some number?
vec(vec==value) = somenumber;
or increment it
vec(vec==value) += 1;
or scale it by ten
vec(vec==value) *= 10;
or remove it from the vector
vec(vec==value) = [];
etc ...
Ben
More information about the Help-octave
mailing list