Hi guys,
First I apologize if my question seems stupid but I'm really stuck here. I want to check whether a number is in a vector or not, what is the command in GAUSS? I know in Matlab there is find
function and in R there is %in%
, but I tried searching these keywords and couldn't find any.
1 Answer
0
You have a few options, depending on what exactly you are looking to do.
Find if one or more elements in a matrix match a specific value
// Vector to search in
haystack = { 1, 2, 4, 5, 6 };
// Does 'haystack' contain the number 3?
has_3 = contains(haystack, 3);
// Does 'haystack' contain the number 6?
has_6 = contains(haystack, 6);
// Does 'haystack' contain either 3 or 4?
needles = { 3, 4 };
has_34 = contains(haystack, needles);
After the code above:
has_3 = 0 has_6 = 1 has_34 = 1
Find the indices of elements which match a value in a vector
indexcat
will the location of elements in a vector from a specified range. Note that the range can be a single number.
// Create a vector
x = { 1, 2, 4, 5, 6, 4, 2 };
// Set 'found' equal to index location
// of 4 in 'x', or return a missing value
idx = indexcat(x, 4);
After the code above:
idx = 3 6
Find the indices of elements which match one or more values in a vector
If you want to locate more than one element inside of a vector, you can use indnv
.
// Create a vector
x = { 1, 2, 4, 5, 6, 3 };
// Elements we are looking for in 'x'
what = { 3, 5 };
// Set 'found' equal to a 2x1 vector,
// containing the index of each element
// of 'what' in 'x' or a missing value
// if it was not found
found = indnv(what, x);
After the code above:
found = 6 4
Your Answer
1 Answer
You have a few options, depending on what exactly you are looking to do.
Find if one or more elements in a matrix match a specific value
// Vector to search in
haystack = { 1, 2, 4, 5, 6 };
// Does 'haystack' contain the number 3?
has_3 = contains(haystack, 3);
// Does 'haystack' contain the number 6?
has_6 = contains(haystack, 6);
// Does 'haystack' contain either 3 or 4?
needles = { 3, 4 };
has_34 = contains(haystack, needles);
After the code above:
has_3 = 0 has_6 = 1 has_34 = 1
Find the indices of elements which match a value in a vector
indexcat
will the location of elements in a vector from a specified range. Note that the range can be a single number.
// Create a vector
x = { 1, 2, 4, 5, 6, 4, 2 };
// Set 'found' equal to index location
// of 4 in 'x', or return a missing value
idx = indexcat(x, 4);
After the code above:
idx = 3 6
Find the indices of elements which match one or more values in a vector
If you want to locate more than one element inside of a vector, you can use indnv
.
// Create a vector
x = { 1, 2, 4, 5, 6, 3 };
// Elements we are looking for in 'x'
what = { 3, 5 };
// Set 'found' equal to a 2x1 vector,
// containing the index of each element
// of 'what' in 'x' or a missing value
// if it was not found
found = indnv(what, x);
After the code above:
found = 6 4