Indexing with logical vectors. Given random vector variables named vecA and vecB
ID: 3598777 • Letter: I
Question
Indexing with logical vectors. Given random vector variables named vecA and vecB, with random values. Some of the elements in vecA and vecB have negative values, which we want to remove. Two approaches will be practiced here. Note that you can use either a logical vector to do indexing directly, or you can use find along with the logical vector. See the previous problem, part (8) Approach l: Selecting only the elements with positive or zero values. Overwrite original variable with the new one Create a variable named logvecA, so its elements will be true for elements in vecA being positive or zero, otherwise the elements in logvecA will be false Use the logical vector logvecA to index desired elements in vecA, and store the result in the variable named vecA. Note: as a result, we lose access to the old vector vecA . . o One example of many possible vecA: vecA = 0 5 -2 7 -4 (original values) logvecAs 1x5 logical array (0 for negative values, otherwise 1) vecA = (after removing negative elements) Approach 2: Removing negative elements from the original variable directly. Create a variable named logvecB, so its elements will be true for negative elements in vecB, otherwise false. Note: logvecA is the "opposite/inverse" of logvecB Use the logical vector logvecB to index negative elements in vecB, then use the empty matrix [] notation to remove these elements. Note: the original vecB is thus modified. . . o One example of many possible vecB 7 -2 0 -1 4 (original values) logvecB = 1x5 logical array (1 for negative values, otherwise 0) (after removing negative elements)Explanation / Answer
This Question is implemented using java programming Language.
Created Two Vectors(VecA & logvecA) and on the behalf of logical vector's index we removed the negative elements from original vector.the running code is given below:
if stuck any where then reply me.
package CheggQuestion;
import java.util.*;
public class LogicalVector {
public static void main(String[] args)
{
int dynsize=0;
Vector<Integer> vecA=new Vector<>();
Vector<Integer> logvecA=new Vector<>();
vecA.add(0);
vecA.add(5);
vecA.add(-2);
vecA.add(7);
vecA.add(-4);
dynsize=vecA.size();
for(Integer obj:vecA) //for encode the value of vecA to 0 and 1
{
if(obj>=0)
{
logvecA.add(1);
}
else
{
logvecA.add(0);
}
}
for(int i=0;i<logvecA.size();i++)
{
if(logvecA.get(i)==0)
{
if(i<dynsize-1)
{
vecA.remove(i);
}
else
{
vecA.remove(i-1);
}
}
dynsize = vecA.size(); //it is taken beacuse on every remove operation the size of vecA changed so we have to //take updated size of the vecA
}
System.out.println(logvecA);
System.out.println(vecA);
}
}