Search array

Hello all,
I have a problem regarding to search array.
It seems like he is unable to find certain elements in the 1D array I deliver. 
Because it outputs -1.
I attached my vi + the file
Koen
UnCertified LabVIEW Student
Mistakes are for learning, that's why suggestions are always welcome!
Solved!
Go to Solution.
Attachments:
Problem.vi ‏17 KB
test2.txt ‏135 KB

You can't accurately do an equals comparison with floating point numbers.  It is just a limitation of floating points in gereral (all computer languages have this issue).  What you should do instead is check to see if a value is in a certain range to account for this limitation.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines

Similar Messages

  • Search Array with multiple values

    Hello,
    I've been helped with the prototype below by blemmo (thanks).
    It allows me to search my array using one property == a
    value.
    Now, I'd like to use it to:
    if ((prop1 == val1) &&(prop2 == val2) &&
    (prop3 == val3) {
    // search array for all values in array with the values of
    val1, val2 and val3
    Also, a way to search if one of the prop and val's are blank,
    ie...
    ((prop1 == val1) &&(prop2 == val2) && (prop3
    == val3)
    where prop2 and val2 are "undefined"
    so the search will only search for the prop and val that are
    not "undefined"
    make since? Don't know where to start.
    help and thanks in advance.

    it is an array like this.. but with more properties... also,
    is it better to use XML to load large arrays or is it ok to use
    actionscript in the file.
    which is faster to load? say if I had an array of 150
    elements?
    myArray = [{myname:"bob", county:"skagit", city:"Sedro
    Woolley", id:1,
    pic:"1.jpg",pic1:"2.jpg",pic2:"3.jpg",pic3:"4.jpg"},
    {myname:"bob", county:"skagit", city:"Sedro Woolley", id:1,
    pic:"1.jpg",pic1:"2.jpg",pic2:"3.jpg",pic3:"4.jpg"

  • Problem searching array

    I have an array in a column that I extracted from a data file. I want
    to search the array for particular values and return the index which
    is easily implemented by the search 1d array subvi. However, when I
    input the values to search, it returns a -1 for some values and others
    it finds fine where I know all the values exist. To be more precise,
    my array is about 80 values between -2 and 2 in steps of 0.05. When I
    search for -2, -1.5, -1, etc., I get the correct index. When I search
    for other numbers like -1.8, -1.7, -1.85, etc., I get a return value
    of -1. It is really strange and I am not sure of the problem. Anyone
    have any ideas? Does it have anything to do with the precision or how
    I read the spreadsheet file to extract the column?
    T
    hanks
    Heather

    Thanks for all your help. I ended up converting both the search array
    and the search element to strings with 2 decimal point precision and
    it works fine.
    You guys are the best.
    Heather
    [email protected] (H) wrote in message news:<[email protected]>...
    > I have an array in a column that I extracted from a data file. I want
    > to search the array for particular values and return the index which
    > is easily implemented by the search 1d array subvi. However, when I
    > input the values to search, it returns a -1 for some values and others
    > it finds fine where I know all the values exist. To be more precise,
    > my array is about 80 values between -2 and 2 in steps of 0.05. When I
    > search for -2, -1.5, -1, etc., I get the correct index. When I
    search
    > for other numbers like -1.8, -1.7, -1.85, etc., I get a return value
    > of -1. It is really strange and I am not sure of the problem. Anyone
    > have any ideas? Does it have anything to do with the precision or how
    > I read the spreadsheet file to extract the column?
    >
    > Thanks
    > Heather

  • Searching arrays using ascii

    I am trying to solve a book problem. I created an array with letters and numbers and I'm supposed to figure out how to count the number of letters in the array. I tried the following code:
    public class ArrayBasics1
      public static void main(String[] args)
         char[] myChar = {'1','2','3','a','b','c','d','e','f'};
         int count = 0, uncount = 0, x = 0;
         for(x = 0; x < myChar.length; ++x)
           //myChar[x] = (char)x; Doesn't work
           if(myChar[x] > 96 && myChar[x] < 123)
              count += 1;
           else
                   uncount += 1;
           System.out.println("The number of letters in myChar is " + count);
           System.out.println("The number of characters in myChar which are not letters is " + uncount);
    }  I think I'm searching the subscripts rather than the content of the array. Any help would be appreciated.

    I just ran your code and it gave the output:
    The number of letters in myChar is 6
    The number of characters in myChar which are not letters is 3
    This looks good to me - what were you expecting? I'm not sure what you were trying to do with "//myChar[x] = (char)x; Doesn't work", but you don't need that line.
    One improvement you might want to make is to use the Character.isLetter() method which also includes upper case letters. e.g. replace
    if(myChar[x] > 96 && myChar[x] < 123)with
    if (Character.isLetter(myChar[x]))Good Luck

  • Search Array of String for exact match words

    I need to create a search feature.
    There will be a textfield where the user will input a word or words.
    Then I need to check if the are any reference in the array of names.
    namesArray ["ocean in the sky", "cean on sky", "cean is white"];
    keywordsArray ["cean", "sky"];
    matchCounter = 0;
    If I input the word "cean" I dont want in my results "ocean in the sky", only "cean is sky".
    I have the following code:
    for (var j:int = 0; j < namesArray.length; ++j)
         var tempStr:String = namesArray[j];
         for (var k:int = 0; k < keywordsArray.length; ++k)
              if (tempStr.indexOf(arrayKeywords[k]) != -1)
                  matchCounter++;
         if(lengthKeywords == matchCounter)
              trace("yeahhh... there's a match!!");
         matchCounter = 0;
    Is there a better way? How can I do this?

    There are few things but the main problem is that "new RegExp()" needs double escapes ("\\")
                var namesArray:Array = ["ocean in the sky", "cean on sky", "cean is white"];
                var keywordsArray:Array = ["cean", "sky"];
                for (var j:int = 0; j < namesArray.length; j++){
                    var matchCounter:uint = 0;
                    var tempStr:String = namesArray[j];
                    for (var k:int = 0; k < keywordsArray.length; k++){     
                        var regExp:RegExp = new RegExp("(\\s+|^)" + keywordsArray[k] + "(\\s+|$)"); 
                        if (tempStr.search(regExp) > -1){
                            matchCounter++;
                    if(keywordsArray.length == matchCounter){
                        trace("\"" + namesArray[j] + "\" matched all the keywords");
    Traces:
    "cean on sky" matched all the keywords

  • Compare and search array

    Hallo
    I have to compare a input data and the ideal data. so far i have understood how to do comparision but the problem create when ideal array have same element with different respective value , similarly input dat are appears to be also same but while doing search in final output array  in 3 column looks different than as it should be.
    hope you understand my problem
    thanking you
    BR
    kalu
    Solved!
    Go to Solution.
    Attachments:
    array%20(modified)[1].vi ‏17 KB

    Hi Kalu,
    Check the attached VI. Let me know if it helps.
    Regards,
    Nitz
    (Give Kudos to Good Answers, Mark it as a Solution if your Problem is Solved)
    Attachments:
    array (modified)[1].vi ‏17 KB

  • Bug when searching array of refnum

    This one just bit me so I thought I should share.  It looks like the Search 1D Array function behaves unexpectedly when used with an array of VI refnums.  So far I have only reproduced it in LabVIEW 2009 SP1, but I ran some code in 8.6.1 that seemed to have the same symptoms.
    When I run the code above, I always get a zero for the output "index of element".  In the example shown I expect to get 3.  In fact if you change that 3 on the array index to any number, you get zero on the output.  My workaround is to typecast the refnum array to an array of I32 and also typecast the refnum that I'm searching for.  That makes it work, but I'm still freaked out by the odd behavior.
    Note that the VI you throw the snippet into must be reentrant.  I believe the search is getting confused because the refnums all point to the same VI, albeit different instances of that VI.  Of course, that is the whole point of using the search 1D array function.  I am trying to identify a particular instance. 

    Photon Dan wrote:
    This one just bit me so I thought I should share.  It looks like the Search 1D Array function behaves unexpectedly when used with an array of VI refnums.  So far I have only reproduced it in LabVIEW 2009 SP1, but I ran some code in 8.6.1 that seemed to have the same symptoms.
    When I run the code above, I always get a zero for the output "index of element". 
     I believe the search is getting confused because the refnums all point to the same VI, albeit different instances of that VI.  Of course, that is the whole point of using the search 1D array function.  I am trying to identify a particular instance. 
    Somewhat poor assumption.
    "Different instances of the same vi"  It Would be more correct to say the referances are all the same as they point to the same constant.  Therefore since A [] are all the same you are returning the first match index 0.
    Probe the array to confirm.
    Turn on "Show constant folding" to see that the Loop doesn't really run 
    Jeff

  • How to search array of control refs

    I have an event case that handles a number of controls of different types in the user interface. I have a global array that holds references to each of several ring controls; I'd like to test whether the control that triggered the event is one of the ring controls.
    I can use a while loop, and control the CtlRef for the event to each ref in my global array--that works fine. But it seems that the Search 1D Array operator would be a natural choice, cleaner and likely faster than a while loop. However, I get a type mismatch when I hook the array of ring refs and the incoming CtlRef to the search function. I tried casting to more specific type on the CtlRef--to a ring ref--but that didn't fix it. Any ideas?

    tst wrote:
    You should have gone the other way. When you have an event common to several types of controls, the CtlRef terminal will use the class common to all those controls, so you should cast the references to the more generic class. The cleaner solution, however, is to use the equal node to compare the array of references to the CtlRef terminal and then search the resulting array for T.
    Yes, I did consider that I should be going to more general, but it seemed that I couldn't do that to the array in one shot, so it would have bought me nothing over the sub-optimal solution that already worked. The conversion to the array with the compare node I hadn't considered though, and that's an excellent solution--thank you much :-)

  • How to write & search array data in a file

    hi
    Can anyone give me an idea about writing an array into a file by placing
    each array element in a line and how to search an array element
    from that file.
    Thanks in advance

    Well, you can serialize any object - and of course re-read it.
    See http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html for an example.
    The easiest way would be to create an encapsulating object, which you then fill with any data you want to serialize. For example:
    class mySerializableContainer implements Serializable{
       public int[][] myArray;
       public String name;
    }All you have to do, is to make sure that every attribute you want to serialize also includes the Serializable interface.
    So, you don't write one Array after another in your file, but only one object - but make this object as flexible as you need to.

  • Re: Sorting a searched array

    If allowed you could write several Compartors and use Collections.sort()
    If not then you will have to write several of your own sort methods. Whatever logic you would have placed in the Comparators you would place in your sort methods. If it is the logic you are having problems with:
    Sort by X
    If 1.X and 2.X are the same then sort by Y
    If 1.Y and 2.Y are the same then sort by Z
    etc.

    Hello,
    Thanks for helping! I'm getting the logic you wrote. But when I sort by arrays, then I will need to run a for loop in order to shift the elements right? I'm not understanding how to set the condition for the 'for' loop. For example, if I have a total of 5 records in the inventory and only 3 of them satisfy the search..then I can run a loop as follows:
    public void SortProduct()
    for(int i=0;i<3;i++)
        if(inventory.getProductName==inventory[i+1].getProductName)
    sortModel();
    But the number of searched elements may differ from time to time, right? Like when user enters another product, and only two records satisfy the criteria, then the loop condition should become for(int i=0;i<2;i++). I'm not getting how to dynamically change the value so the loop runs for any number of elements depending on the search results at that time.
    Also, is my sort method right? I'm not too good at it.
    Edited by: Beginner_Troubles on Apr 17, 2008 7:59 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Searching arrays

    i need to search an array for an element and then i need to search it again without the result of the previous one.
    for example array is a,b,c,d and i search for b. then the next time i search i can only search a,c,d but b is still in the array: it is just excluded from the search. this search will go on until all the elements have been excluded.
    how do i implement that ?
    do i create another dimension in the array ?
    please help
    thanks

    do you need to get the index or just return the
    element.
    I would use a collection such as ArrayList, make a
    clone if you desire and when an object is found,
    remove it from the clone before subsequent searches.
    walkervery kludgy, and when dealing with huge arrays, memory intensive
    could make a small class dealing with the actual item your sticking in the array, and give it a bool.
    this is only if you know of what type of objects will be in the array
    this example is for if your using ints
    public class intOnOff () {
    public int val;
    public boolean on = TRUE;
    public intOnOff ();
    //here is your array
    intOnOff[] array = new intOnOff[5000000]; //forgive me if my array sytax is wrong, i havnt used arrays in some time
    for(int i = 0; i < array.Length; i++) {
    if(valueYourLookingFor == array.val && array[i].on) {
    array[i].on = FALSE;
    return array[i]; //or whatever you wanna do... you could put this function form easily
    Hope this helps

  • Using indexOf( ) to search arrays

    I would like to know, can you get an index of an array? for example, if I have typed:
    String ay = "A";
    String[] numArray = { "A", "B", "C", "D", "E", "F" }
    , can I then write:
    if (ay.indexOf("A") != -1) {
    do-something
    else {
    do-something-else
    if this is possible, it would certainly save me a lot of time when performing validation!

    There is a static method binarySearch in java.util.Arrays. Guess it does what you need.
    I would like to know, can you get an index of an
    array? for example, if I have typed:
    String ay = "A";
    String[] numArray = { "A", "B", "C", "D", "E", "F" }
    , can I then write:
    if (ay.indexOf("A") != -1) {
    do-something
    else {
    do-something-else
    if this is possible, it would certainly save me a
    lot of time when performing validation!

  • Searching arrays (different)

    I have some code which shows menus using switch statements. I am able to select a number from that menu and then move onto another menu.
    But then when I want to search for an item in a list of 5 boats (say I wanted to search if I wanted to buy a boat) I am not sure what to do.
    boats boats1 = new boats((byte)5,(short) 6600, true);
    boats boats2 = new boats((byte)4, (short)2400, false);
    System.out.println("\nSelect 1 to search for a boat, \nSelect 2 to rent a boat,"
         switch (number)
                        case 1:System.out.println("Search for a boat"); break;
                        case 2:System.out.println("Rent a boat"); break;
                        case
                        default: System.out.println("Not a valid Input");
         if (number == 1)
                        System.out.println("\nSelect 1 to search for the length of the boat");
                                                           So if i wanted to search for the length of a boat (byte) then do I do Loops (ifs) to search in my field of 5 boats.

    I see, I still get a bounds error when I get to this part. Do I have to create any variables or should it search in the list?
                             if (number == 1)
                             for (int n =0;n<5;n++) ;
                             System.out.print("\nPlease enter the length you wish to search for: ");
                             boats[5] = EasyIn.getInt();
                             }

  • SEARCH ARRAY AND COUNT TRANSITION FROM HIGH TO LOW

    I have 4 dig inputs.  I want to count the number of times each individual input transitions from high to low and display the count  I attached the vi as v11.  Thanks for any help.
    Solved!
    Go to Solution.
    Attachments:
    count.PNG ‏94 KB
    9422_Digital_In_mod.vi ‏52 KB

    Hello Jootbox,
    Are you by any chance using a cDAQ 9181 chassis?
    If you are it might be a good idea to use the 4 counters internally available on this chassis.
    A simple example about counting edges can be found over here:
    https://decibel.ni.com/content/docs/DOC-11412
    Kind Regards,
    Thierry C - Applications Engineering Specialist Northern European Region - National Instruments
    CLD, CTA
    If someone helped you, let them know. Mark as solved and/or give a kudo.

  • How to search for particular string in array?

    I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
    The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
    Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
    // ==========================================================
    // Tool class
    // Reads user input from keyboard and writes to text file a list of entered
    // inventory items (tools)
    // ==========================================================
    import java.io.*;
    import java.text.DecimalFormat;
    public class Tool
    private String name;
    private double totalCost;
    int units;
      // int record;
       double price;
    // Constructor for Tool
    public Tool(String toolName, int unitQty, double costPrice)
          name  = toolName;
          units = unitQty;
          price = costPrice;
       public static void main( String args[] ) throws Exception
          String file = "test.txt";
          String input;
          String item;
          String addItem;
          int choice = 0;
          int recordNum = 1;
          int qty;
          double price;
          boolean valid;
          String toolName = "";
          String itemQty = "";
          String itemCost = "";
          DecimalFormat fmt = new DecimalFormat("##0.00");
          // Display menu options
          System.out.println();
          System.out.println(" 1. ENTER item(s) into inventory");
          System.out.println(" 2. DELETE item(s) from inventory");
          System.out.println(" 3. DISPLAY item(s) in inventory");
          System.out.println();
          System.out.println(" 9. QUIT program");
          System.out.println();
          System.out.println("==================================================");
          System.out.println();
          // Declare and initialize keyboard input stream
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
          do
             valid = false;
             try
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
                valid = true;
             catch(NumberFormatException exception)
                System.out.println();
                System.out.println(" Only numbers accepted. Try again.");
          while (!valid);
          while (choice != 1 && choice != 2 && choice != 9)
                System.out.println(" Not a valid option. Try again.");
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
          if (choice == 1)
             // Declare and initialize input file
             FileWriter fileName = new FileWriter(file);
             BufferedWriter bufferedWriter = new BufferedWriter(fileName);
             PrintWriter dataFile = new PrintWriter(bufferedWriter);
             do
                addItem="Y";
                   System.out.print(" Enter item #" + recordNum + " name > ");
                   toolName = stdin.readLine();
                   if (toolName.length() > 15)
                      toolName = toolName.substring(0,15); // Convert to uppercase
                   toolName = toolName.toUpperCase();
                   dataFile.print (toolName + "\t");
                   do
                      valid = false;
                      try
                         // Prompt for item quantity
                         System.out.print(" Enter item #" + recordNum + " quantity > ");
                         itemQty = stdin.readLine();
                         // Parse integer as string
                         qty = Integer.parseInt (itemQty);
                         // Write item quantity to data file
                         dataFile.print(itemQty + "\t");
                         valid=true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-integer input
                         System.out.println();
                         System.out.println(" Only whole numbers please. Try again.");
                   while (!valid);
                   do
                      valid = false;
                      try
                         // Prompt for item cost
                         System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
                         itemCost = stdin.readLine();
                         // Parse float as string
                         price = Double.parseDouble(itemCost);
                         // Write item cost to data file
                         dataFile.println(fmt.format(price));
                         valid = true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-number input (integers
                      // allowed)
                         System.out.println();
                         System.out.println(" Only numbers please. Try again.");
                   while (!valid);
                   // Prompt to add another item
                   System.out.println();
                   System.out.print(" Add another item? Y/N > ");
                   addItem = stdin.readLine();
                   while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
                      // Prompt for valid input if not Y or N
                      System.out.println();
                      System.out.println(" Not a valid option. Try again.");
                      System.out.print(" Add another item? Y/N > ");
                      addItem = stdin.readLine();
                      System.out.println();
                   // Increment record number by 1
                   recordNum++;
                   if (addItem.equalsIgnoreCase("N"))
                      System.out.println();
                      System.out.println(" The output file \"" + file + "\" has been saved.");
                      System.out.println();
                      System.out.println(" Quitting program.");
            while (addItem.equalsIgnoreCase("Y"));
    // Close input file
    dataFile.close();
       if (choice == 2)
       try {
          Read user input (array search string)
          Search array
          If match found, remove entry from array
          Confirm "deletion" and display new array contents
       catch block {
    } // class
    // ==========================================================
    // ListToolDetails class
    // Reads a text file into an array and displays contents as an inventory list
    // ==========================================================
    import java.io.*;
    import java.util.StringTokenizer;
    import java.text.DecimalFormat;
    public class ListToolDetails {
       // Declare variable
       private Tool[] toolArray; // Reference to an array of objects of type Tool
       private int toolCount;
       public static void main(String args[]) throws Exception {
          String line, name, file = "test.txt";
          int units, count = 0, record = 1;
          double price, total = 0;
          DecimalFormat fmt = new DecimalFormat("##0.00");
          final int MAX = 20;
          Tool[] items = new Tool[MAX];
          System.out.println("Inventory List");
          System.out.println();
          System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
                + "PRICE" + "\t" + "TOTAL");
          System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
          System.out.println();
          try {
             // Read a tab-delimited text file of inventory items
             FileReader fr = new FileReader(file);
             BufferedReader inFile = new BufferedReader(fr);
             StringTokenizer tokenizer;
             while ((line = inFile.readLine()) != null) {
                tokenizer = new StringTokenizer(line, "\t");
                name = tokenizer.nextToken();
                try {
                   units = Integer.parseInt(tokenizer.nextToken());
                   price = Double.parseDouble(tokenizer.nextToken());
                   items[count++] = new Tool(name, units, price);
                   total = units * price;
                } catch (NumberFormatException exception) {
                   System.out.println("Error in input. Line ignored:");
                   System.out.println(line);
                System.out.print(" " + count + "\t");
                System.out.print(line + "\t");
                System.out.print(fmt.format(total));
                System.out.println();
             inFile.close();
          } catch (FileNotFoundException exception) {
             System.out.println("The file " + file + " was not found.");
          } catch (IOException exception) {
             System.out.println(exception);
          System.out.println();
       //  Unfinished functionality for displaying "error" message if user tries to
       //  add more than 20 tools to inventory
       public void addTool(Tool maxtools) {
          if (toolCount < toolArray.length) {
             toolArray[toolCount] = maxtools;
             toolCount += 1;
          } else {
             System.out.print("Inventory is full. Cannot add new tools.");
       // This should search inventory by string and remove/overwrite matching
       // entry with null
       public Tool getTool(int index) {
          if (index < toolCount) {
             return toolArray[index];
          } else {
             System.out
                   .println("That tool does not exist at this index location.");
             return null;
    }  // classData file contents:
    TOOL 1     1     1.21
    TOOL 2     8     3.85
    TOOL 3     35     6.92

    Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
    Is that right?
    Can you use an ArrayList<String> instead of a String[ ]?
    To find it, you would just do:
    for (String item : myArray){
       if (item.equals(searchString){
          // remove the element. Not trivial for arrays, very easy for ArrayList
    }Heck, with an arraylist you might be able to do the following:
    arrayList.remove(arrayList.indexOf(searchString));[edit]
    the above assumes you are using 1.5
    uses generics and for each loop
    [edit2]
    and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
    Message was edited by:
    BaltimoreJohn

Maybe you are looking for