Indentifing vector or matrixes elements that accomplish a given codition

Say that I have a matrix or vector of elements with random numbers between 0 and 100. And I want to identify the elements bigger than 75.6. Is there a way to do this different than a loop?

1 Answer



0



Depending upon your goals, you can use either an element-by-element logical comparison or the function indexcat.

Logical comparison operator

//Create a 7x1 vector
x = { 12,
      91,
      67,
      24,
      68,
      82,
      44 };

cutoff = 75.6;

//Create a 7x1 vector with a
//one for any element > 75.6
//and a zero otherwise
mask = x .> cutoff;

After this code snippet, mask will equal

0
1
0
0
0
1
0

You can use the selif function with this mask variable to get a new vector which only contains the elements which are greater than your cutoff. Continuing with our example above

x2 = selif(x, mask);

will create a new vector, x2, equal to

91
82

indexcat function

indexcat returns the row indices of a vector which are in a specified range. For example, using our x from above

//Find indices of rows in 'x' with elements greater than 75.6
//and less than positive infinity
idx = indexcat(x, 75.6 | __INFP);

which will set idx equal to

2
6

aptech

1,773

Your Answer

1 Answer

0

Depending upon your goals, you can use either an element-by-element logical comparison or the function indexcat.

Logical comparison operator

//Create a 7x1 vector
x = { 12,
      91,
      67,
      24,
      68,
      82,
      44 };

cutoff = 75.6;

//Create a 7x1 vector with a
//one for any element > 75.6
//and a zero otherwise
mask = x .> cutoff;

After this code snippet, mask will equal

0
1
0
0
0
1
0

You can use the selif function with this mask variable to get a new vector which only contains the elements which are greater than your cutoff. Continuing with our example above

x2 = selif(x, mask);

will create a new vector, x2, equal to

91
82

indexcat function

indexcat returns the row indices of a vector which are in a specified range. For example, using our x from above

//Find indices of rows in 'x' with elements greater than 75.6
//and less than positive infinity
idx = indexcat(x, 75.6 | __INFP);

which will set idx equal to

2
6


You must login to post answers.

Have a Specific Question?

Get a real answer from a real person

Need Support?

Get help from our friendly experts.