Methods to build an array inside a For Loop.

Let me introduce to you my nested For Loops:  
They output a 2D boolean array depending on two 1D boolean arrays of different lengths.  This is all well and good however, in another part of my program, I want this to be a 1D array instead.
Idea #1:
"I'll just reshape the array at the end. Simples!"
Idea #2:
"Hang on, why am I using three primitives outside the loop when I can use just one inside it along with a shift register?"
Idea #2.5:
"Oh, wait... I remember reading somewhere about continuously building an array (with concatenate inputs) inside a loop being a bad thing and quite slow. Let me test this."
Spoiler (Highlight to read)
Idea #3:
"Umm... okay, so actually the second way is faster.  I think if I initialize the shift register first then replace subsets of the array, that might also be better."
Spoiler (Highlight to read)
Idea #4:
"Yep - seems much better. (Something to do with LabVIEW not having to constantly allocate more memory on every iteration of the loop)  Looking at this closer, I don't actually need the inner For Loop because of the way I'm handling the arrays.  Try again...!"
Spoiler (Highlight to read)
Conclusion(?) #1:
"Well I seem to have arrived at something that looks messier, but executes about 6x faster than my initial idea. That said, the difference rapidly increases as the input arrays get much bigger (becoming orders of magnitude different)."
Is this the most efficient way of doing what I want?  Or is there something even better (and works in LV 8.5)?
Never say "Oops." Always say "Ah, interesting!"

Thank you both for the feedback.  It never occurred for me to recheck the logic after I'd initially extracted the nested For Loops, but the AND gate output is obviously the same now that it's been pointed out!
Continuing on with Idea #4, I replaced the Select with an AND then compared the times.  (also meant I didn't have to initialize one of the arrays anymore)
Spoiler (Highlight to read)
It appears that the AND gate was slower but then I tried with different sizes of initial arrays and in one case, the timings were 'reversed'.
This only happened when the top array (the one that is fed into the AND gate whole) was reduced to a length in the region of 5 elements long.
Spoiler (Highlight to read)
Why does this happen?  Is it something to do with the AND gate possibly being optimised for single element operations so smaller arrays are handled better...?
Never say "Oops." Always say "Ah, interesting!"

Similar Messages

  • Building an array from a for loop.

    Hi all
    I have a vi which reads from a file and manipulates the data using for loop. I am taking each element and multiplying it with a constant and converting it to I32. I would like to build back to a new array with the new values. I have attached the vi and a sample data file to read from.
    Please suggest if there are any better ways to do this.
    Thank you. 
    Solved!
    Go to Solution.
    Attachments:
    file_read.vi ‏11 KB
    file_read.txt ‏1 KB

    You can multiply the array with the constant and use the array instead of multiplying it with each element.
    The best solution is the one you find it by yourself

  • How to build an array inside a loop

    Hi everyone,
    I have a basic question about labview. I would like to create an array in a "for" loop in that way:
    inside the loop, if a condition named "A" is verified, then, i add a new value to the first column of the array.  Otherwise, i create a new column, and start to add values to this column when the condition "A" is verified, etc.
    I put an example of a VI where the condition "A" is "the increment of the loop + 1 is not divisible by 5" and the values of the arrays are the increment of the loop + 1. The loop stops when the increment = 25.
    In this example, i have a single column with the values [1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19 21 22 23 24]
    while I would like to have an array of 5 columns:
    1   6   11   16   21
    2   7   12   17   22
    3   8   13   18   23
    4   9   14    19   24
    Note than this is just an example. More generally, the array can contain columns of different lengths.
    Thanx for your answer
    Andrew
    Solved!
    Go to Solution.
    Attachments:
    build_array.vi ‏9 KB

    You can't have columns in an array have different lengths - you can dynamically increase the size of the array (e.g. build array) but it means you will get the default value of the array in the other columns up to the new size of the array (normally 0).
    You will need to either keep track of the last index you wrote to for each column so you can trim it later or put an array in a cluster and then create an array of those (an array of a cluster of an array) - that will allow your column data array to have different lengths and you'll just need to unbundle/bundle the array before adding new items.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • Creating an array in a 'for' loop (resetting loop count)

    Hi,
    I am trying to integrate an acceleration signal coming from a CRIO analogue input to obtain the speed and then further integrate to get the displacement of a vibration system.
    I understand that in order to perform the integration, an array has to be fed in. My problem is that I could not buffer the signal in a buffer block as I couldn't find any buffer blocks. so I decided to create my an array of data using a 'for' loop. The 'for' loop nests inside a timed loop. The problem that I got stuck at is how to reset the 'for' loop in order to refill the buffer again at every iteration of the outer timed loop.
    I have attached the code if that helps. Note that I am using labview 2013.
    I would be gratefull if someone who had encountered a similar issue before can help me.
    Regards
    Ali
    Solved!
    Go to Solution.
    Attachments:
    acc_test.vi ‏42 KB

    Dear Altenbach,
    Many thanks for your reply.
    I need to make it clear that I have not had enough hands-on with labview, I have only used it for sometime in the past and now I have to in order to perform some active damping on a 50Hz running machine. I must stress the fact that what i find more intuitive to do in a different programming language (matlab or C) is not as straightforward in labview. so please bear with me if my code has basic mistakes .
    All what i am trying to do is obtain the speed and position from an acclerometer signal. unfortunately i dont have a position sensor so i have to measure acceleration then perform time integrations in order to obtain the speed and position respectively. I am using a compact Rio (later in FPGA mode) to take physical measurements of acceleration from the vibratory machine and where i managed to do this bit successfully. when it came to performing the integration, i had to create an array inside my timed loop since i couldn't find a buffer block. I implemented a 'for' loop inside a timed loop in order to build the array. however i got stuck at resetting the count of the 'for' loop in order to refill the array with new values at every new iteration of the outer timed loop. unfortunately, even a sensible answer has been suggested before, i dont seem to have been capable of doing it yet. I really spent all my day trying to figure a way out but not achieved it yet, nevertheless I have learnt many many things by playing around.
    I would be gratefull if you could comment on a possible way of doing what i am trying to do.
    Kind Regards
    Ali

  • Truncating an array within a for loop

    I'm currently working with a program that builds an array of 3000*N real numbers, where N is a control that I specify. I want to pass this array into a for loop that runs N times, each time splitting the first 3000 numbers of the array. So, in other words I want the for loop to execute enough times such that the initial array will be completely divided into groups of 3000 when I'm finished. Later I'll be finding the maximum value of all of these subarrays and taking the average of those. What I tried first is to pass the array into the for loop, then truncate it at index = 3000, but the problem is that I can't hard code the loop to do this N times. Any advice or other methods you'd recommend for doing this?
    Thanks.
    Message Edited by Robtn on 03-05-2010 03:17 PM

    Mark--I don't think I can use that approach. Let me be more specific on what the problem is:
    Our "big program" is a giant while loop that constantly reads in voltage values from a DAQ assistant.
    It has two modes, the first of which I'm having a lot of trouble with. This mode uses a for loop (N = 3000) nested within the giant while loop.
    When the for loop activates, the DAQ assistant takes reads 300 samples for every iteration and takes the maximum of those 300 values. It then builds an array composed of all the maxima. After the for loop has executed 3000 times, a case structure activates, which then finds the maximum of the array of maxima.
    I want this (N=3000) for loop to execute an arbitrary number of times, a number that I will specify. Each of those times it should generate a completely seperate array of maxima. So, if I want the for loop to run 5 times, I want 5 different arrays.
    My approach for doing this was to change N=3000 to say N = 15000, then split up the resulting array 5 times. So, I need an entirely separate for loop that reads in this array of 15000 maxima on its own and splits it 5 ways. I think what you're suggesting is to use a for loop outside of the N=3000 loop, which is a good idea in theory, but experience has shown that this will not generate 5 separate arrays. It will actually concatenate each array into one, hence the problem we currently have.
    Yik--I won't have access to Labview over the weekend. Is it possible to take a screenshot and post it, or maybe a short description?
    Thank you for the responses.

  • Why are date and time strings lost when indexing an array in a for loop

    Hi, 
    I have an application where i'm reformatting data from a spreadsheet for graphical display on a LabVIEW dashboard.
    the original spreadsheet has date and time values in separate columns, and i'm merging them and converting to a timestamp value.  But something's not working.  Does anyone know why the string value is lost when the array indexes into this for loop?
    Attachments:
    failed array index.png ‏142 KB

    Can you attach your VI with some typical values? (e.g. create in indicator on the 2D array, run your VI, then turn the indicator (now containing data) into a diagram constant). Place the FOR loop related code and that diagram constant into a new VI and attach it here.
    How many times does the FOR loop run? Could it be that the last element of each 1D array is an empty string? (unless you put a wait inside the FOR loop, you'll never see the other elements in the probe)
    LabVIEW Champion . Do more with less code and in less time .

  • Row operation on array with a For Loop

    Hi,
    I'm working with a large one dimensional column array. I'm trying to do the following
    for i=1:size(A)/2
    B(i,: ) =A(1+(i-1)*2:i*2)
    So, for example if
    A=          
    0
    1
    2
    3
    4
    5
    6
    7
    then
    B=             
    0 1
    2 3
    4 5
    6 7
    My approach was to use an array subset block inside the for loop to select a number of elements but I'm not sure how to transpose the selected elements into a new row to create the new array B. Is there a more straightforward approach?
    Thanks,
    Mike
    Solved!
    Go to Solution.

    try experimenting with the reshape array feeding it your input array and re-sizing it to output a 2d aray. It is much faster than using a For loop becuase the data never gets moved and LV just changes the array dimensions and updates the stride.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Transposing data in an array using a For Loop

    I am trying to transpose some data in an array using a  for loop starting from the size of the array then decrement down to 0. Can someone please help if you have an example?
    Solved!
    Go to Solution.

    I feel as if reverse 1D array may help
    Edit: misunderstood what your second post meant.
    CLA, LabVIEW Versions 2010-2013

  • How to speed up my code inside the for loops,

    how to speed up my code inside the for loops using c# WinForm.

    Hi  John,
    Please take a look at the reply from Wyck in the following thread.
    How to speed up for loop?
    His answer is very comprehensive.   Thanks.
    Best regards,
    kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to use String Tokeniser inside this for loop?

    [i][i]hi there..
    i am reading all the file inside a directory and get the latest modified file than i have to tokenise it and juz read the number. For example my file name that is last modified will be abc_123.txt but i just want it to appear 123.
    i manage to do it separately how can i put the tokeniser inside my for loop?
    my directory
    for (int i = 0; i < files.length; i++)
                        if(files[i].isFile())
                             if(lastModifiedFile == null){
                             lastModifiedFile = files[i];
                             String mylastModifiedFile = lastModifiedFile.toString();
                             StringTokenizer tokens = new StringTokenizer (mylastModifiedFile,".");
                             String modified = tokens.nextToken().substring(modified.length-4);*/
                             if(lastModifiedFile != null)
                                  if(lastModifiedFile.lastModified() < files[i].lastModified())
                                       lastModifiedFile = files[i];
    my tokeniser is this
    String mylastModifiedFile = lastModifiedFile.toString();
                             StringTokenizer tokens = new StringTokenizer (mylastModifiedFile,".");
                             String modified = tokens.nextToken().substring(modified.length-4);*/
                   }

    [i][i][i]hi there..
    i am reading all the file inside a directory and get ...
    tokens.nextToken().substring(modified.length-4);*/
                   }[/i][i][/i][/i][/i]Is there some reason for this baroque formatting? Please use the
    code tags as explained in one of your other threads on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=793441&messageID=4510858#4510858

  • Real-time updates of an XY graph with a 2D array (x,y) inside a for-loop

    Hi all,
       I am new to this forum, and relatively new to LabView (I've used TestPoint in the past), and I have a question. I have implemented a for-loop to grab data from an LCR meter (via GPIB) which becomes the Y data. The X data is calculated and tunneled into the for loop (although varies with incrementing 'i'). Anyhow, I am trying to store all of the data and keep the user updated throughout the test by plotting the XY Graph each iteration. Right now, the XY Graph plots one point at a time, so somehow the data I am appending to the 2D array (x,y data) is getting overwritten each itteration. How can I make it so that each new point is added to the array, making it bigger so that the data will be saved and so that the user will be able to see all the data in real-time on the graph as the test in running?
    Thanks
    P.S. I would post a screenshot, but I'm not sure how to upload here.

    Hey Mendeleev3104,
    There is an attachment section at the bottom of the post when creating or editing a post. You might want to use that to attach a picture of your code.
    None the less I will give a shot with some suggestions without viewing your code.
    You should look into using shift registers along with the Insert Into Array.vi to build an array of numbers. A good source of information for shift registers can be found in the For Loop and While Loop Structures help.
    Hopefully this helps!!
    Aashish M
    Applications Engineer
    National Instruments
    http://www.ni.com/support/

  • Building 2D array in a while loop

    I'm trying to build an array from hex data received from a serial device(using VISA) inside a while loop.  Can I take the hex string(262 bytes long) and write it into the first element of an array?  Everytime the loop is executed the next hex string  I would like to store  it into the next element of the array. Can someone give me some hints on how to get started or a basic vi that outlines building an array of this type in a while loop.  Thanks. 

    Where is the 2D aspect of this? What you're describing sounds like a 1D array, and you can just use auto-indexing to do this.
    To learn more about LabVIEW it is recommended that you go through the tutorial(s) and look over the material in the NI Developer Zone's Learning Center which provides links to other materials and other tutorials. You can also take the online courses for free.
    Message Edited by smercurio_fc on 04-11-2008 04:07 PM
    Attachments:
    Example_VI_BD2.png ‏2 KB

  • How to index array in a for loop

    i'm connecting from variant-to-data function to an index array function inside a for_loop (refer to attachment).  the data-type wire got converted from Table(2-D array) to Table(1-D array).  How do I keep it from converting to 1-D array?
    Attachments:
    arrayI.doc ‏146 KB

    Of course it seems you want to run the loop once for each row in the 2D array, so many times autoindexing is the better solution!
    You are using an "index array" inside the loop. If you are planning to wire the index to the iteration [i] terminal (who knows? ), you might as well use autoindexing. This way you don't need to wire N (the loop will know how many rows there are) and you don't need to use index array inside the loop.
    The image shows two functionally equivalent code fragments. Autoindexing (bottom) is much simpler than explicit indexing (top). See if autoindexing can work in your case.
    Since you are a LabVIEW beginner, you should try to stay way from stacked sequences and local variables. They are rarely needed and can ofter cause problems such as race conditions and unreadable code.
    Message Edited by altenbach on 03-31-2008 04:17 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    autoindexing.png ‏8 KB

  • How to output last 4 arrays from a For Loop?

    Hi People,
    I am almost at the end of my tether. I really hope someone could please help me.
    Any input would be welcome. VI attached.
    VI explanation:
    I initialize an array.
    The random number generator simulates my camera input.
    Depending on which iteration it is, the data is added into one of four output arrays.
    'x-y*floor(x/y)' gives a remainder value of 0, 1, 2 or 3.
    'Case Selector' just adds 1 to 'x-y*floor(x/y)' to get case 1, 2, 3 or 4.
    Shots 1, 5, 9 etc are added to Array 1 (Case 1).
    Shots 2, 6, 10 etc are added to Array 2 (Case 2).
    Shots 3, 7, 11 etc are added to Array 3 (Case 3).
    Shots 4, 8, 12 etc are added to Array 4 (Case 4).
    Averaged Output displays the averaged value i.e. the total value divided by the number of shots saved in that array ('Set (IQ+1)').
    My problems are:
    1) I would like to output only the last 4 sets of data from the Averaged Output 1, 2, 3 and 4 to 4 different files (i.e. save as .csv what is displayed onscreen in indicators 'Averaged Output 1', 2, 3 and 4 at the end of all iterations.
    Where should I place my file save diagram disable so that it does this?
    Putting it outside the main For Loop with auto-indexing on gives me one file with all previous data. (This is not feasible as my number of shots should number in the thousands)
    Putting it outside the main For Loop with auto-indexing off gives me only the last set of data. (I need the output for 4 Arrays, not just the last run)
    Putting it inside the main For Loop (as shown) gives me the same number of files as number of iterations. (Again not feasible due to large number of files that will be generated and slow camera capture)
    For the sake of fast camera capture, I would like these 4 files to only output once all the image captures are complete.
    2) Would preferably like to name the file once and for the programme to append '(1)', '(2)', '(3)' and '(4)' to filename of the appropriate 'Averaged Output' Arrays but file path controls are another big headache for me.
    3) P.s. is initializing one array enough to avoid using Memory Manager? Or should I initialize 4 arrays?
    I am using Labview 2010.
    Thanks so much,
    Jaslyn
    Solved!
    Go to Solution.
    Attachments:
    Help Understanding Arrays and file paths (10).vi ‏26 KB

    Thanks so much Lennard!!
    Hi JKSH,
    I've been busy trying to complete the dang code, but for completeness so that other users can learn too, I shall answer your queries. Thanks for looking in.
    First, what do you mean by "add"? Your code in your case strcuture sums your input values, so your array size doesn't change. However, you also said "Putting it outside the main For Loop with auto-indexing on gives me one file with all previous data. (This is not feasible as my number of shots should number in the thousands)" -- it sounds like you are expecting an array with thousands of elements. So, what should "Output Array N" look like?
    Ans: Output Array N should be a 4x4 array of the summation of all the numbers generated during every 4th iteration.
    i.e. if random number 1=1, random number 2=2, etc, And 'No of iterations' is 12,
    Output Array 1 should be 1+5+9:
    15 15 15 15
    15 15 15 15
    15 15 15 15
    15 15 15 15
    (Note: Most of your arrays are 4x4, but in Case #2 you created 128x128. I prersume this is a typo?)
    Ans: Kind of, I'm using a 4x4 array of randomly generated numbers as an example but my actual data will be the 128x128 pixel output of a camera. And during actual experimentation, 'No of Iterations' will number in the thousands.
    Second, why do you add your "simulated camera input" to the "Initialized Array"? You can add it direcly to the previous output inside your case structure.
    Ans: See answer to question 3
    Third, have a look at shift registers: http://www.ni.com/gettingstarted/labviewbasics/shiftregisters.htm. Use them instead of Feedback Nodes to make your code tidier.
    Ans: I did try.. But I can't seem to add shift registers to the case structure, only the for loops outside. Are you sure it can be done..?
    jaslyn wrote:
    1) I would like to output only the last 4 sets of data from the Averaged Output 1, 2, 3 and 4 to 4 different files (i.e. save as .csv what is displayed onscreen in indicators 'Averaged Output 1', 2, 3 and 4 at the end of all iterations.
    Where should I place my file save diagram disable so that it does this?
    For the sake of fast camera capture, I would like these 4 files to only output once all the image captures are complete.
    You will need to call "Write to Text File.vi" 4 times to write 4 files. So, you should finish your loop, then call this VI 4 times.
    Ans: How do I get it to extract the data from each of the 4 cases in my case structure?
    jaslyn wrote:
    2) Would preferably like to name the file once and for the programme to append '(1)', '(2)', '(3)' and '(4)' to filename of the appropriate 'Averaged Output' Arrays but file path controls are another big headache for me.
    You can create strings first, then convert them into paths: http://zone.ni.com/reference/en-XX/help/371361G-01/glang/string_to_path/
    Thanks
    jaslyn wrote:
    3) P.s. is initializing one array enough to avoid using Memory Manager? Or should I initialize 4 arrays?
    I'm not sure what you're asking; can you please clarify what you mean by "avoid using Memory Manager"? But anyway, you've actually initialized FIVE arrays: 1 outside the loop, and 1 inside each case.
    I've read that to avoid fluctuations in memory usage, it is a good idea to initialize arrays to their expected size before the start of data collection. That was just what I was trying to do.

  • Passing an array in a for loop to a procedure

    I am trying to pass an array in a cursor for loop to a procedure which performs a table insert using the array's contents. Somehow I am missing something, or it is not possible. The compile error states: PLS-00306: wrong number or types in call to 'insert_address' I checked to be sure I am creating the arrays in both cases from similar data objects. Both address and work_address_table contain the same 4 columns with the same data types.
    create or replace package work_address as
    FUNCTION populate_address return boolean;
    procedure insert_address(in_address IN work_address_table%ROWTYPE);
    end work_address;
    create or replace package body work_address as
    function populate_address return boolean is
    cursor c1 is
    select 'H' as header,
    street1 as street
    city as city,
    NULL as state
    from address
    where city = 'HANOVER';
    TYPE addressT IS TABLE OF c1%ROWTYPE INDEX BY BINARY_INTEGER;
    rec1 addressT;
    BEGIN
    OPEN c1;
    FETCH c1 BULK COLLECT INTO rec1 LIMIT 500;
    FOR i IN 1..rec1.count LOOP
    rec1(i).state := 'US'
    insert_address(rec1(i));
    exit when c1%notfound;
    END LOOP;
    CLOSE c1;
    return TRUE;
    END populate_address;
    PROCEDURE insert_address(in_address IN work_address_table%ROWTYPE) IS
    BEGIN
    INSERT INTO work_address_table
    VALUES (in_address.header,
    in_address.street,
    in_address.city,
    in_address.state);
    COMMIT;
    END insert_address;
    END work address;
    /

    Both address and work_address_table contain the same 4 columns with the same data types.Are you 100% sure about this?
    SQL> declare
      cursor c1
      is
        select 1 deptno, dummy dname, 'Loc' location from dual;
      type addresst is table of c1%rowtype
        index by binary_integer;
      rec1   addresst;
      procedure p (d dept%rowtype)
      as
      begin
        dbms_output.put_line(d.dname);
      end p;
    begin
      rec1 (1).dname := 'z';
      p (rec1 (1));
    end;
    z
    PL/SQL procedure successfully completed.but changing just the first column of the cursor:
    SQL> declare
      cursor c1
      is
        select 'xy' deptno, dummy dname, 'Loc' location from dual;
      type addresst is table of c1%rowtype
        index by binary_integer;
      rec1   addresst;
      procedure p (d dept%rowtype)
      as
      begin
        dbms_output.put_line(d.dname);
      end p;
    begin
      rec1 (1).dname := 'z';
      p (rec1 (1));
    end;
    Error at line 3
    ORA-06550: line 20, column 3:
    PLS-00306: wrong number or types of arguments in call to 'P'
    ORA-06550: line 20, column 3:
    PL/SQL: Statement ignored

Maybe you are looking for

  • Slow to a crawl in the Discussions Forum

    Today has been maddeningly slow . It was taking a few minutes to just open a subject , a couple times I timed out and/or the site appeared to actually go down . I am finding it strange that I don't see much mention of this . At first I thought it was

  • Macbook Pro 15 "(late 2011) failure of the graph?

    I have a Macbook Pro 15 "late 2011. Anyway, yesterday suddenly working with photoshop choppy with many stripes screen mode interference stayed. Thing goes off and no longer gray top with window apple and can distinguish some weird lines in the backgr

  • PDF gaining file size when "optimizing"

    I have a PDF that I'm trying to reduce the size of, the original size is around 6 MB, when I have "optimized" the size actually increased anywhere from 9MB to 15MB. There were a few attempts that I do get it to a lower size, but along with that there

  • HT4623 i cant find the software update option in between about and usage?

    Hello am useing a Apple i phone 3GS , i want to upgrade the option from 4.2 to any new versions? plz support me to get it

  • Problems with pages after installing OS X Mavericks

    I have thousands of individually written invoices in pages on my MAC. When I installed OS X Mavericks the headers don't appear when I open them and doesn't appear on my templates. It would take forever to open each document and alter them. There are