Fast way to find the number of non-zero terms in an array or image

I am trying to use the Standard Deviation PtbyPt Vi.  It takes in a series of points, can be reset when beginning the calculation.  There is also an input for sample size.  I am calculating some statistics on an array...and would only  to include like the non-zero elements that are  in the sample. 
Is there a quick way to look at an array and find the number of non-zero elements?
Thanks.
Solved!
Go to Solution.

GerdW wrote:
- for big arrays this may lead to "out of memory" problems because of creation of data copies
Here's a quick rundown on memory allocations based on the algorithm.
(case 1&3)
If you do the "!=0, ?1:0, I32, sum" shuffle, each step needs to allocate a new array, so if the input array is DBL and uses N amount of memory, we need 7N/8 more memory.
(Total of 15N/8, or 13N/8 if we don't need the I32, but in this case the array are too small to worry about anything )
The nice thing is that it works for any array dimensionality (1D, 2D, 5D, etc...)
(Case 2&5)
If you do the summing in a shift register, No additional array memory is needed. Unfortunately, the code needs to be changed by adding an extra FOR loop for each dimension (see case 5 for 2D inputs).
(Case 4)
If we reshape the N-D array to a 1D array, we need to create a second copy, so the memory usage is about twice. This also works for any dimension.
In real life, and if memory is a potential issue, you should always do some benchmarks.
Often, the issues are more complex, so this is just a quick summary.
Message Edited by altenbach on 10-23-2008 11:59 AM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
CountNonZero.PNG ‏29 KB

Similar Messages

  • Finding the number of Non-Blank Line in a File

    Does anyone know the command or how to find the number of non-blank lines in a text file? I have the program already reading characters, words, and total lines.
              BufferedReader FileIn = new BufferedReader( new FileReader( selectedFile ) );
                   Scanner scanWords = new Scanner (selectedFile);
                             String thisToken = "";
                             int numWords = 0;
                             while (scanWords.hasNext())
                             thisToken = scanWords.next();
                             numWords++;
         System.out.println("Total number of words: " + numWords);
         Scanner scanLines = new Scanner (selectedFile).useDelimiter("\n");
                             String thisToken2 = "";
                             int numLines = 0;
                             while (scanLines.hasNext())
                             thisToken2 = scanLines.next();
                             numLines++;
         System.out.println("Total number of lines: " + numLines);
         Scanner scanChars = new Scanner (selectedFile).useDelimiter("");
                             String thisToken3 = "";
                             int numChars = 0;
                             while (scanChars.hasNext())
                             thisToken2 = scanChars.next();
                             numChars++;
         System.out.println("Total number of characters: " + numChars);
                   FileIn.close();
              }

    Use BufferedReader#readLine() instead. Read the file once and process each line once.

  • Is there a way to find the number of downloads of music from itunes store?

    Hi,
    Is there any way to find the number of downloads of each music file available on itunes store. If not exact no of downloads but atleast a relative term to find the rank of the music track From any API
    Thanks
    Sandeep

    A: Is there a way to read the number of active sequence executions from the Engine?

    Scott,
    > One way of handling the issue of init once a set of instruments is to
    > create a new sequence file that has a sequence to init and a sequence
    > to close the instruments. Assuming that you always terminate a
    > sequence and do not abort them, you could add a ProcessSetup and
    > ProcessCleanup callback sequences to the client sequence file that
    > using these instruments. These callbacks are automatically called by
    > the process model in both the Single Pass and Test UUTs execution
    > entry points. The callback sequences could call the init and close
    > sequences for the hardware. In the hardware sequence file you could
    > reference count the number of execution that init and close by setting
    > the file globals in the sequence file to be shared across executions
    > and then add a numeric value that keeps track of references for the
    > instruments. The init sequence adds to the count, and the close
    > sequence subtracts from the count. The init sequence inits the HW if
    > the count is 0->1 and the close sequence closes the HW if the count is
    > 1->0.
    >
    > This is one of many ways in TestStand that this could be done, not to
    > mention that this could also be done in a similar way in a LabVIEW VI
    > or DLL directly.
    That sounds like it will work. I'll try adding a client count
    increment/decrement in the DLL initialize and terminate functions. This
    should essentially perform the same tasks as the callback scheme you mention
    above, no?
    The reason I didn't think the 'client counting' scheme would work initially
    was I mistakenly thought that the termination function would not get called
    under Terminate conditions. Since Terminate conditions happen a LOT during
    our initial debug of new UUT types, I didn't think that would be acceptable.
    I forgot that lacing the terminate funciton in a cleanup step group, I can
    force it to be called in Terminate conditions.
    > If you abort an execution then the reference counting idea above would
    > fail to decrement properly. That might b... [Show more]

    Read other 5 answers

  • How to find the number of pending messages in a Queue

    All,
    Is there a way to find the number of pending messages in a given QUEUE to be picked by the queue reader?
    My reader is not picking all the messages as many sent by my writer, i am not sure where they are getting lost? or if the JMS implementation is buffering them and does not flush until it does not have enough to throw out ( which any way does not make sense!!).
    Please help.
    Chandra

    You're right in thinking that the behaviour you describe looks wrong.
    Take a look at the QueueBrowser interface which can be used to inspect a queue. You get one using QueueSession.createBrowser(Queue). The QueueBrowser allows you to scan a queue without consuming the messages. However note that the state of the queue may change while you're observing it through the QueueBrowser so what you see might not always be a 100% accurate representation of the queue at any given time.
    Other things to check:
    - message selectors - are you setting a message selector on your queue receiver which is resulting in not all of the messages 'matching'.
    - expired messages - are you setting a time-to-live on the messages that you publish.
    Hope this helps,
    David Ingham
    http://www.arjuna.com

  • Is there a way to find the class objects memory size?

    Hi Friends,
    Please help.
    Is there a way to find the number of Objects created and total size?
    For example:
    class AgeRecord
    int start;
    int end;
    AgeRecord(int start, int end)
    this.start = start;
    this.end = end;
    In a loop if I create 1000 objects, how will I get the total memory size
    Thanks and Regards
    JG

    You might find this useful...
    package forums;
    http://weblogs.java.net/blog/dwalend/archive/2007/11/the_thing_about.html
    http://forums.sun.com/thread.jspa?threadID=457279&start=30&tstart=0
    http://www.velocityreviews.com/forums/t364574-size-of-boolean-type.html
    The JLS doesn't specify the size of a boolean, leaving it upto the JVM
    implementor to define. Sun's JVM stores booleans as:
    (1) a boolean is-an int; i.e. a signed 32 bit twos-compliment integer.
        At face value, this is an innordinate waste of space, but Java uses a
        32-bit stack frame, and most (modern) CPU's use a 32-bit word anyway,
        so the wasted space is worth the CPU cycles, and it's simple.
    (2) a boolean[] is-a byte array, using 1 byte per element, rounded up to the
        nearest 8, plus 8 bytes for the array-object itself.
        For example: boolean[] bools = boolean[100];
        100 mod 8 = 4; so that'd be 104 bytes + 8 bytes = 112 bytes.
        So, let's dis/prove the contention by experiment.
        1,000,000 mod 8 = 0 so 1,000,000 + 8 bytes for the array = 1,000,008
    class BooleanArraySizeTest
      public static void main(String[] args) {
        final Runtime rt = Runtime.getRuntime();
        System.out.println("The contention is that each iteration should use 1,000,008 bytes.");
        try {
          long before, after;
          final int TIMES = 32;
          boolean[][] bools = new boolean[TIMES][];
          for (int i=0; i<TIMES; i++) {
            before = rt.totalMemory() - rt.freeMemory();
            int n = 1000*1000-(TIMES/2)+i;
            bools[i] = new boolean[n];
            after = rt.totalMemory() - rt.freeMemory();
            System.out.print(n);
            System.out.print('\t');
            System.out.print(after-before);
            System.out.println();
        } catch (Exception e) {
          e.printStackTrace();
    999984 used=1000000 bytes
    999985 used=1000000 bytes
    999986 used=1000000 bytes
    999987 used=1000000 bytes
    999988 used=1000000 bytes
    999989 used=1000008 bytes
    999990 used=1000008 bytes
    999991 used=1000008 bytes
    999992 used=1000008 bytes
    999993 used=1000008 bytes
    999994 used=1000008 bytes
    999995 used=1000008 bytes
    999996 used=1000008 bytes
    999997 used=1000016 bytes
    999998 used=1000016 bytes
    999999 used=1000016 bytes
    1000000 used=1000016 bytes
    1000001 used=1000016 bytes
    1000002 used=1000016 bytes
    1000003 used=1000016 bytes
    1000004 used=1000016 bytes
    1000005 used=1000024 bytes
    1000006 used=1000024 bytes
    1000007 used=1000024 bytes
    1000008 used=1000024 bytes
    1000009 used=1000024 bytes
    1000010 used=1000024 bytes
    1000011 used=1000024 bytes
    1000012 used=1000024 bytes
    1000013 used=1000032 bytes
    1000014 used=1000032 bytes
    1000015 used=1000032 bytes
    ENVIRONMENT:
      Microsoft Windows [Version 6.0.6000]
      Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
      C:\Users\Administrator>java -version
      java version "1.6.0_12"
      Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
      Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
    */Cheers. Keith.

  • A quick way to count the number of  newlines '/n' in string of 200 chars

    I am trying to establish the number of lines that a string will generate.
    I can do this by counting the number of '/n' in the string. However my brute force method (shown below) is very slow.
    Normally this would not be a problem on a 2800mhz Athlon (Standard) PC this takes < 1 second. However this code resides within a speed critical loop (not shown). The code shown below is a Achilles heal as far as the performance of this speed critical loop goes.
    Can anyone suggest a faster way to count the number of �/n� (new lines) within a text string of around 50- 1000 chars, given that there may be 10 � 100 newline chars. Speed is a very important factor for this part of my program.
    Thanks in advance
    Andrew.
        int lineCount =0;
        String txt = this.getText();
        //loop throught text and count the carridge returns
        for (int i = 0; i < txt.length(); i++)
          char ch = txt.charAt(i);
          if (ch == '\n')
           lineCount ++;
        }//end forMessage was edited by:
    scottie_uk
    Message was edited by:
    scottie_uk

    Well, here is a C version. On my computer the Java version (reply 9 above) is slightly faster than C. YMMV. For stuff like this a compiler can be hard to beat even with assembler, as you need to do manual loop unrolling and method inlining which turn assembly into a maintenance nightmare.
    // gcc -O6 -fomit-frame-pointer -funroll-loops -finline -o newlines.exe newlines.c
    #include <stdio.h>
    #include <string.h>
    #if defined(__GNUC__) || defined(__unix__)
    #include <time.h>
    #include <sys/time.h>
    #else
    #include <windows.h>
    #endif
    #if defined(__GNUC__) || defined(__unix__)
    typedef struct timeval TIMESTAMP;
    void currentTime(struct timeval *time)
        gettimeofday(time, NULL);
    int milliseconds(struct timeval *start, struct timeval *end)
        int usec = (end->tv_sec - start->tv_sec) * 1000000 +
         end->tv_usec - start->tv_usec;
        return (usec + 500) / 1000;
    #else
    typedef FILETIME TIMESTAMP;
    void currentTime(FILETIME *time)
        GetSystemTimeAsFileTime(time);
    int milliseconds(FILETIME *start, FILETIME *end)
        int usec = (end->dwHighDateTime - start->dwHighDateTime) * 1000000L +
         end->dwLowDateTime - start->dwLowDateTime;
        return (usec + 500) / 1000;
    #endif
    static int count(register char *txt)
        register int count = 0;
        register int c;
        while (c = *txt++)
         if (c == '\n')
             count++;
        return count;
    static void doit(char *str)
        TIMESTAMP start, end;
        long time;
        register int n;
        int total = 0;
        currentTime(&start);
        for (n = 0; n < 1000000; n++)
         total += count(str);
        currentTime(&end);
        time = milliseconds(&start, &end);
        total *= 4;
        printf("time %ld, total %d\n", time, total);
        fflush(stdout);
    int main(int argc, char **argv)
        char buf[1024];
        int n;
        for (n = 0; n < 256 / 4; n++)
         strcat(buf, "abc\n");
        for (n = 0; n < 5; n++)
         doit(buf);
    }

  • Is there a way to find the serial number in these files so that I can reinstall the full version?

    I had to restore from backup to a new hard drive, and only have part of my Adobe Photoshop installation. Is there a way to find the serial number in these files so that I can reinstall the full version?  I have only part of the documentation so this is the best way I see to get the full version back.

    Hello brad,
    you did purchase your product from these firms like Amazon, so you didn't get a serial number, only a code with which you can request a serial number from Adobe. Please have a look at http://helpx.adobe.com/x-productkb/global/find-serial-number.html. (Start here: How did you purchase your product?)
    The following part, so I just see at least, ceased to exist on my Adobe website, everything takes place in the link from above. I leave it as an info yet, it might still fit for you. For this purpose, please click your way through to your Adobe Store and find the button "Get Serial Number". Fill in the form and after a while you will get the real serial number.
    Additionally you should have a look at Adobe's database, to see what's stored/saved about your accounts. Here you will find general infos about your Adobe Account.
    On the other hand, if necessary and for further questions click through http://helpx.adobe.com/contact.html and if "open" please use the chat, I for may part had the best experiences. I quote from Adobe's employee Preran: The chat button is activated as soon as there is an agent available to help.
    Hans-Günter

  • Someone had my apple id password and bought a game from the App Store. I've changed my password but is there any way to find he number it was downloaded to?

    Someone had my apple id password and bought a game from the App Store. I've changed my password but is there any way to find he number it was downloaded to?

    Contact iTunes support

  • Is there any way to find the serial number of an ipod touch that is no hooked up to the computer?  It was stolen and we need the number to give to the police.

    Is there any way to find the serial number of an ipod touch that is no hooked up to the computer?  It was stolen and we need the number to give to the police.

    If the product was registered, the serial number should be here, under My Products:
    https://supportprofile.apple.com/MySupportProfile.do

  • HT4061 Is there another way to find the serial number with only your apple ID and password because apparently I never backed up my iPhone 5?

    Is there another way to find the serial number with only your ID and password because apparently I never backed up my device on my computer?

    If you registered it with Apple, you could try:
    supportprofile.apple.com
    Use your Apple ID and password to log in

  • HT1391 Is there a way to find the serial number for a devise from ITunes? I need it to try and track it as it was stolen

    Is there a way to find the serial number for a devise from Itunes? I need the number for a device that was stolen.

    How to find serial number

  • How to find the number of data items in a file written with ArryToFile function?

    I have written an array of number in 2 column groups to a file using the LabWindows/CVI function ArrayToFile...Now if I want to read the file with FileToArray Function then how do I know the number of items in the file. during the write time I know how many array items to write. but suppose I want the file to read at some later time then How to find the number of items in the file,So that I can read the exact number and present it. Thanks to all
    If you are young work to Learn, not to earn.
    Solved!
    Go to Solution.

    What about:
    OpenFile ( your file );
    cnt = 0;
    while ((br = ReadLine ( ... )) != -2) {
    if (br == -1) {
    // I/O error: handle it!
    break;
    cnt++;
    CloseFile ( ... );
    There are some ways to improve performance of this code, but if you are not reading thousands of lines it's quite fast.
    After this part you can dimension the array to pass to FileToArray... unless you want to read it yourself since you already have it open!
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How to find the number of occurance of a string in text field of Infopath form?

    Hi All,
    In Infopath text field, How to find the number of occurrence of a particular string in that field?
    Thanks in advance!

    You can check to see if it contains a string once by using the contains function, but there isn't a very clean way to do what you want. If you wanted to guess at the maximum number of occurrences, then you could:
    Box A has your initial. Set Box B to do a concat of string-before and string-after of Box A where it copies Box A minus the string we're looking for. Then we have Box C that does the same thing to Box B. Repeat as many times as you see necessary.
    Example:
    String: "1"
    Box A - "123451234512345"
    Box B - "23451234512345"
    Box C - "2345234512345"
    Box D - "234523452345"
    etc.
    We then have a field that has nested ifs looking backwards from Z -> A looking for a non-blank. Based on that, we return the number of occurrences. Again, this isn't clean, but it will work if you think there's a predefinable maximum.
    Andy Wessendorf SharePoint Developer II | Rackspace [email protected]

  • How do I find the number of contacts in a smart group?

    How do I find the number of contacts in a smart group in Contacts?

    Hi,
    To get the depth using JMS you must create a QueueBrowse and browse the entire queue. Its generally horribly inefficient if you want to do it with any regularity.
    In Hermes I have had to write plugins that open separate connections to providers using their non-JMS APIs or JMX and get that kind of information that way.
    Look at the getDepth() method in this JBoss plugin for an example that uses JMX:
    http://cvs.sourceforge.net/viewcvs.py/hermesjms/Hermes4/src/java/hermes/ext/jbossmq/JBossMQAdmin.java?view=markup
    And here is one for WebSphereMQ that uses one of its many APIs..
    http://cvs.sourceforge.net/viewcvs.py/hermesjms/Hermes4/src/java/hermes/ext/mq/MQSeriesAdmin.java?view=markup
    Colin.
    http://hermesjms.com

  • How to find the number of times method being called.....

    hi,
    can any one pls tell me how to find the number of times the method being called......herez the example....
    Refrence ref = new Refrence();
    for(int i = 0;i < arr.length; i++){
    if(somecondition){
    ref.getMethod();
    here i want to know how many times the getMethod() is calling...Is there any method to do this.. i have seen StrackTraceElement class..but not sure about that....pls tell me the solution....

    can any one pls tell me how to find the number of times the method being called......
    herez the example.... http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal ? in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

Maybe you are looking for

  • IBooks hyperlinks don't work anymore

    After upgrading iBooks, my proof iBooks have disappeared on the iPad, but even worse, all hyperlinks (opacity 0%) don't work anymore. Is there a solution? Regards, Linda

  • How to restore Macboo pro (Lion) defautl keyboard command settings?

    Hi there, I am not sure what happend, but all of the sudden my default keyboard commands are not following the "defaut settings" already in place on my mac... Example, when I use the screen capture, (commnad+4) it kick me back to the previous page, a

  • Apple TV cannot load my Itunes lybrary

    First of all I´m in Brazil and some things do not work as in US. My Apple TV 2 suddenly cannot see (load) my Itunes lybray. I´ve already tried many tricks and nothing seems to work. Restarted all devices, used different account but nothing really wor

  • Preview Window to PDF

    I want to have a canvas in flex where i can add/remove text and images and move them so that i create a cover page which i can then send somewhere. Two step process. 1. Live Design the cover page 2. Send it to a pdf generator. any ideas on this would

  • Exchange 2007 - Edit Dynamic Distribution Group

    Hello everyone, I would like to edit a dynamic distribution group, the only way possible it seems is through the command shell. In the EMC on the properties of the dynamic distribution group on the Filter tab, I copied the data in the Recipients Filt