Possible threadsafe issues using Matlab scripts?

Hi all,
I'm developing an application in Labview 6.1 that makes extensive use
of Matlab scripts.  The application executes the same set of
scripts for multiple data sources, and keeps track of the inputs and
outputs for each data source separately.  I've been noticing that
the application produces the correct results when running only one data
source, but that the results are often incorrect when I run it against
multiple data sources.
I've done some investigation, and have found that all Matlab scripts
share a common memory workspace in Matlab.  That is to say that if
I have ScriptA that takes variable X as an input, and ScriptB that does
not, ScriptB nonetheless has access to variable X in its workspace
(from the last time ScriptA was called).  This doesn't pose a
problem to me directly, but it has made me wonder if there are
potential threading issues in the scripts.
Consider the following scenario with one script and two data
sources.  I'm wondering if this scenario is possible in Labview:
1.  Thread1 calls ScriptA, passing data from SourceX.
2.  During Matlab execution (somewhere in the middle), Thread1 is suspended.
3.  Thread2 calls ScriptA, passing data from SourceY (data have the same variable names, since it's the same script).
4.  Thread2 finishes ScriptA execution uninterrupted with SourceY data.
5.  Thread1 is reactivated, but now the Matlab workspace data has
been replaced with SourceY.  So, Thread1 started with SourceX
data, but finished with SourceY data.
6.  An incorrect result for Thread1 is produced, because the wrong data was processed.
Clearly I could get around this problem with a semaphore, but first I'd
like to know if this scenario can even happen.  Are Matlab scripts
treated as atomic operations in Labview, or can the threads be
suspended midway through execution?
Thanks for your help!
cjb

Hello,
No. LabVIEW will definitely not compile a VI while it's running - I think that would be, even conceptually, impossible.  In fact, some properties (accessed via property nodes) are not editable at run-time for basically that reason, that a recompile would be necessary in order for the affect to take place, and the recompile can't take place at run-time!
It is indeed strange behavior, particularly because it is intermittent (which does hint at a threading issue, or some factor outside the development environment).  Can you try moving the initialization to LabVIEW?  I have attached an example of a so-called functional global variable (a simple code module in this case).  It has two "states" (which are cases) - one is initialize and the other is the "usually executing case."  The initialize case is used to initialize the shift register to an array of 50 doubles, where the other case will compute the running average, min, and max across the 50 most recent random numbers generated.  The 50 data point code module.vi is the code module, and it is called by Use 50 data point code module.vi.  When you run Use 50 data point code module.vi, be sure to toggle the initialize boolean so that the initialize case executes once to allocate and initialize an array with 50 elements; when you toggle it back then it will execute the other case on each iteration, and begin computing the statistics noted by keeping an array with the 50 most recent random data points generated.
I hope this helps and that you are able to incorporate a similar code module into your application to avoid the intermittent errant behavior!
Best Regards, and feel free to post again with updates!
JLS
Best,
JLS
Sixclear
Attachments:
Use 50 data point code module.zip ‏27 KB

Similar Messages

  • How to load a variable using MATLAB Script?

    I need to load a selected variable from .mat file, using MATLAB script , and analyse it.
    the attched shows my vi, there are two inputs nodes 'file' contains the .mat file path, and 'varn' contains varibale name in that .mat file which can be selected by user. Using " load(file)" the whole .mat file is loaded in the workspace and become avaiable at output node, however I am not able to pass a selected variable name through string "varn" input, MATLAB script does not recognize the variable.
    any idea to reslove it is realy appreciated.
    Attachments:
    load a variable.JPG ‏18 KB

    Download the VI and .MAT file. Run the VI, and it'll plot the data inside of the .MAT file.
    Andy Chang
    National Instruments
    LabVIEW Control Design and Simulation
    Attachments:
    testfile.zip ‏5 KB

  • How to do complex engineering calculation in labview.I tried using MATLAB script

    Hello,
    I am trying to use matlab script node to solve two complex equation.But i get different  errors everytime i run my program.sometimes 1048 sometimes 1050 and sometimes it says LABVIEW could not extract variable from Matlab.I am attaching  my MATLAB script node with this thread.Please Help me out to get rid of this problem.
    I am  using LV-8 and MATLAB R-2006a.
    Attachments:
    matlab.vi ‏10 KB

    Hi Praween,
    beside my little MatLab knowledge I tried to replace your formula with equivalent LV code...
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    matlab_lv80.vi ‏18 KB

  • Using Matlab script in Labview

    Hello,
    I am trying to use matlab script in labview to post process the sampled signals from DAQ(attached is the vi I tried)
    After every 10 seconds I want to the send the sampled voltage data to matlab scritp block which does 1) detection of peaks using peakdetection function and plots the obtained peaks on the sampled signal 2) calculates standard of 10 secs data and plots on chart.
    But I am confused of 1) how to call the peakdetection function inside the matlabscript block
    2) How to send the 10secs data of voltage and time values to the matlab script block
    3) How to plot the signal and detected peaks on the same plot (which can be done in matlab using holdon as shown in the atached vi).
    Can someone suggest for implementing these .
    Thanks.
    Solved!
    Go to Solution.
    Attachments:
    Labview&Matlab.vi ‏55 KB

    Thanks  GabeG,
    Now, Labview&Matlab_TestNoAq.vi  is woking Good and for the second one  Labview&Matlab_TestAq.vi it is showing error as shown in the attached image when these ines of code are present in the matlab scrtip 
    subplot(2,1,1),plot(maxtab(:,1),maxtab(:,2),'*r');
    SDN=std(maxtab(:,1));
    and SDN output of the Matlab script
    but when I removed these it is working fine(but not showing the detected peaks).
    Can you suggest me a solution for the above and also can I know the best method to add one more channel that samples another device signal which has to be processed in this same way(Signals sampled from 2 devices have to be porcessed in this same way).
    Thanks.
    Attachments:
    Script_Error.JPG ‏133 KB

  • Open a file using matlab script block

    Hello!
    I want to open a file from a specified directory using matlab script block.
    The input of this block is a string with file's name......but it doesn't work in this way. I have to change the input data or I have to change it  into matlab matlab script?
    Some idea?
    Thanks!
    Attachments:
    example.PNG ‏4 KB

    Ooooppss!
    My computer is crazy....sorry.
    I'm near to solve my problem...
    The problem is that I have a column of strings like this
    str=['labview'
            'labview2'
           'labview3'
            'labview4']
    I use the double command but the byte array to string block only converts me an element, do you know is exist another block to change all the elements.
    I've tried to do with a for loop block....using an index array and changing with i the index element, but it doen'st work.
    You have some idea?

  • Using matlab script

    Hello!
    I'm using matlab script block in my aplication. The m-file (from matlab) contain an 'if' that depends of an input of labview.
    I want to pass trough this condition only once when input's value changes, but labview "covert" this 'if' in a 'while' and pass trough this sequence n times.
    How can I to impose to pass throug the sequence once the input's value change. It's better to specifie it from matab or from labview.
    Thank you in adavance 

    What is surrounding the matlab script block? LabVIEW should be modifying the matlab code, it should be connecting with matlab and matlab executes its code, returning the results to LabVIEW. Can you do a screen capture of the part of the code that contains the matlab stuff? If yes make sure that it is saved as a .jpg (not .bmp!) for size reasons. If not, if you can send the part of your code that includes the matlab stuff that would help.
    P.M.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Error (1046) using matlab script

    Hi ,
    im trying to use matlab script Labview , i've got matlab installed.
    when im running the VI , i'm getting an error 1046 , i tried to search the community ,
    and i've been told to check the "choose script server" , i dont know why , but i it's "grayed" ,
    and i cant change anything.

    Cobmetal,
    Looking at the following KnowledgeBase, it looks like MATLAB® may need to be registered as an ActiveX server first.
    http://digital.ni.com/public.nsf/allkb/5BECAA32D63921628625670C005BDA1A?OpenDocument
    Mathworks has good documentation about how to register MATLAB as a COM Automation server in the Windows registry when launched. I would try to do that if the option to choose script server is greyed out (Ctrl+F regserver).
    http://www.mathworks.com/help/matlab/ref/matlabwindows.html
    MATLAB® is a registered trademark of The MathWorks, Inc. Other product and company names listed are trademarks and trade names of their respective companies.
    Matt J
    Professional Googler and Kudo Addict
    National Instruments

  • Creating a random noise (Gaussian) using Matlab Script

    Hello,
    Since I only have Labview 6.1 base, I can't use the white-noise generator in Labview. I'm thinking of using the Matlab Script. I have Matlab 2006R installed in the same computer. However, I tried running the program and nothing happened (I used the help example "a=rand(50);surf(a)" in the Matlab Script.
    Why it's not calling the Matlab, or is there a better way to create a Gaussian distribution in Labview 6.1 Base?
    Thanks a lot!

    Hello,
    Why are you unable to use the Gaussian White Noise VI in LabVIEW 6.1?  It is under the Analyze >> Signal Processing >> Signal Generation palette.  I have attached a simple VI that illustrates creating a matrix.
    If you wish to use the MATLAB® script node, let's first make sure it is working correctly.  Try opening one of the LabVIEW shipping examples.  Browse to <LabVIEW>\examples\scriptnode and open "HiQMATLAB_Fractal.llb."  Then open "MATLAB Fractal.vi."  Run the VI.  Do you get any error windows that pop up?  If not and you see a picture of a fractal appear, then the connection to the MATLAB software is working correctly.  In your VI, try creating an error out indicator from the MATLAB script node and see if any errors appear.
    If you do see an error in the shipping example, it means there is a problem with the software connection.  Make sure that you have launched the MATLAB software at least once after you installed it.  This will set up the necessary connection information.  Then launch LabVIEW.  If this isn't the issue, we could try manually restoring the server commands.  Make sure LabVIEW and the MATLAB software are not running.  Go to a command prompt, browse to the MATLAB bin directory (e.g. MATLAB\R2006b\bin), and type
    matlab -regserver
    Quit the instance of the MATLAB software that appears and launch LabVIEW.  If this also fails, please post again with any error information you receive.
    Also, the rand function in your script will not generate a Gaussian distribution. You will need to use the randn function instead.
    MATLAB® is a registered trademark of The MathWorks, Inc.
    Grant M.
    Staff Software Engineer | LabVIEW Math & Signal Processing | National Instruments
    Edit: For some reason, I am unable to attach the VI.  I have included a picture instead.
    Message Edited by GrantM on 08-08-2008 02:50 PM
    Attachments:
    Gaussian Matrix.png ‏35 KB

  • Intermittent issues with Matlab Script in LV2012

    I'm having some intermittent issues with the Matlab Script in LV2012.  I'm running Windows 7 64 bit, and my Matlab is 2013 64-bit.  I've tried the suggestion here:
    http://digital.ni.com/public.nsf/allkb/8BEBC0C86541224286257AF300561B5E
    I tried this but it didn't work for me. 
    I've also looked at this:
    http://digital.ni.com/public.nsf/allkb/2B3FF46C8512C4F786256CF30071BE53?OpenDocument
    In one of my .vi's if I change 2 of the 3 input variables to the complex type, it works.  It seems to be insensitive to the data type of the first input variable.  In another .vi this trick doesn't work at all.  The fix given in the link is to update the .dll, but this seems to be old news as the .dll in my directory is newer than the one referenced in this link.
    The other funny thing is these scripts worked fine on Friday afternoon, but were throwing this error this morning.  I've closed and reloaded both Labview and Matlab, but that didn't fix the issue.
    Are there any new fixes for this issue that I haven't been able to find?
    Thanks,
    Doug

    Doug,
    If you have a service contract feel free to call in to the support line and you'll be able to work with someone on the phone. That'll be the quickest way to resolution.
    Feel free to send me a PM if you wish and I can take a look at the code and test it on our machine. 
    Notes for Branch AE:
    Please reply to This Post within 24 hours
    The US AE is expected to reply to all of your posts within 24 hours. Having this expectation will keep the escalation moving quickly and toward a fast resolution.
    You can also use other communication channels: Phone, Sametime, Lync,etc. to discuss the issue with the US AE. This can help with troubleshooting and quick diagnosis of the issue.
    Click here to provide kudos for a post on this page

  • Using matlab script block

    Hello!
    I'm using a matlab script block and I have a problem that i don't how to solve it,
    I want to import a column that in matlab is cell array or char array type. When you create an output in matlab script block you have to specify the data type....I choose string, but with this option you can only import one string....and I want to import a whole column.
    Someone knows how I have to do to import this data type? I have to do some changes to the data from matlab or I have to use some especific block in labview to adapt the data.
    Please help me!!
     Thanks!!!

    Ooooppss!
    My computer is crazy....sorry.
    I'm near to solve my problem...
    The problem is that I have a column of strings like this
    str=['labview'
            'labview2'
           'labview3'
            'labview4']
    I use the double command but the byte array to string block only converts me an element, do you know is exist another block to change all the elements.
    I've tried to do with a for loop block....using an index array and changing with i the index element, but it doen'st work.
    You have some idea?

  • Compiler Error with simple vi using MatLab script nodes

    While attempting to build a simple vi to test the capabilities of LabView's interface with MatLab, I received a compiler error message that said I should report the problem to National Instruments Tech Support. The error said, "reference to undefined label from: refPC=0x41C." I've attached the vi that created the error. I am using LabView 7.0 on a PC running Windows 98.
    Attachments:
    Compliererror.vi ‏11 KB

    I don't know if this will help your problem, but there is a fix for some problems with LabVIEW 7.0 and Matlab:
    http://digital.ni.com/public.nsf/websearch/4475BC3CEB062C9586256D750058F14B?OpenDocument
    Good luck,
    -Jim

  • Matlab script error 1050

    Hi All,
    I am using MATLAB Script in LabVIEW. But there is error 1050. 
    Could you take my attached script and figure it out for me? Thanks a lot!
    elephant
    Attachments:
    MATLAB SCRIPT Error.png ‏35 KB

    I am also getting error 1050. The script works fine in Matlab with the same parameters. But in Labview, the following error occurs :
    Error 1050 occurred at LabVIEW:  Error occurred while executing script. Error message from server: ??? Error using ==> mtimes
    Inner matrix dimensions must agree.
    Error in ==> linspace at 22
    y = [d1+(0:n-2)*(d2-d1)/(floor(n)-1) d2];
    . in wgm_Individual_RootSearch.vi
    The script is:-
    format longEng
    [Lre Lim]=meshgrid(lambda0_re,lambda0_im);
    row=0;
    col=0;
    R_=zeros(N1,N2);kco=zeros(N1,N2);kc=zeros(N1,N2);M1=zeros(N1,N2);M2=zeros(N1,N2);
    mn=1e5;%minimum value
    while(mn>tol)
    L=Lre+1i*Lim;%L becomes a 2D mesh with all possible combinations of real and imag
     kco=(2*pi./L)*nco;
            kc=(2*pi./L)*nc;
            M1=nco/2*(besselj(m-1,kco*p1)-besselj(m+1,kco*p1))./besselj(m,kco*p1);
            M2=nc/2*(besselh(m-1,1,kc*p1)-besselh(m+1,1,kc*p1))./besselh(m,1,kc*p1);
            R_=abs(M1./M2 -1)';
    mn=min(R_();
    [row col]=find(R_==mn);
    Dr=lambda0_re(N1)-lambda0_re(1);
    Di=lambda0_im(N2)-lambda0_im(1);
    Lr=lambda0_re(row);
    Li=lambda0_im(col);
    lambda0_re=linspace((Lr-(Dr/20)),(Lr+(Dr/20)),N1);
    lambda0_im=linspace((Li-(Di/20)),(Li+(Di/20)),N2);
    [Lre Lim]=meshgrid(lambda0_re,lambda0_im);
    end
    r=lambda0_re(row);
    c=lambda0_im(col);
    Any hints will be really appreciated.. Where am I going wrong please let me know. Thanks  a lot.
    The parameters are in the screenshot below:

  • Error 1048 Matlab Script depends on string length

    Using: Labview 8.2, Matlab 2007a, Windows XP (AMD X2 4200+ 3GB RAM).
    I'm having an issue with MATLAB script server, Error 1048 failed to get variable from script server.  I've read the forums, but most posts are years old and don't address variable size issues.  I have no problem with these strings inside the MATLAB command window.  I'm somewhat inexperienced with LabView, so maybe this VI could have been simplified.
    I'm writing data files with a tab header, using MATLAB to perform some operations on data (I have a library written to do certain things and can't really spend the time to recode in Labview).  When I try to pass out the new header string, I get error 1048 only when the string length goes above a certain size range.  I have iterations because I want to process hundreds of files in a similar fashion to this VI.
    Header length ~ 1300 chars has always been fine, regardless of number of iterations within the VI.
    Header length ~ 2600 chars presents some errors; not deterministic.
    Header length ~ 5200 chars has many errors; not deterministic.
    Header length ~ 7800 chars has many errors, fails almost all the time.
    Also, timing delay after reading in the file seemed to do nothing to help.  Pausing at the end of the MATLAB script did not seem to help. Clearing MATLAB/restarting LabView did not seem to help.  Is there a way to catch variable-specific errors from the script window?  Notice that the output variable is not cleared when it fails to be obtained from the MATLAB window.  I could wrap the whole thing in a while loop until there are no errors, but that doesn't help when the length is so large none of them succeed.   I can split the string inside matlab, but I'd have to create n strings and then concatenate them outside, which still gives me a lack of scalability.  Is there any better way to handle this kind of non-deterministic error?
    Thanks very much for reading.
    Attachments:
    header6001.txt ‏8 KB
    Matlab Script Server Test1.vi ‏38 KB
    header1001.txt ‏2 KB

    Does NI monitor these forums for bug reports to fix?  Here's a non-scalable hack solution I mentioned earlier, creating n string outputs and concatenating them in Labview.  I've checked this in Matlab using the code below.  I've included the VI if anyone has the same issue and wants it.
    Note that I chose to throw the size error if the string is too large for the n you choose.  I prefer this to trying to check the string output to see if it was truncated.
    hcols = size(hstring,2);
    for k = 1:8
        hvar = strcat('h', sprintf('%d',k));
        if( hcols >  k*1000 & k < 8 )
            hcom = sprintf('%s = ''%s'';', hvar, hstring(1, ((k-1)*1000+1):k*1000 ));
        %if size < k*1000, or we're at the end with leftovers, copy what's left
        elseif( hcols >= (k-1)*1000+1  &  (hcols <= k*1000 | k == 8 ))
            hcom = sprintf('%s = ''%s'';', hvar, hstring(1, ((k-1)*1000+1):end));
        else
            hcom = sprintf('%s = '''';', hvar);
        end  
        eval(hcom);
    end
    %Matlab validation code.  Do not use strcat, as it will chop tabs at the endpoints.
    newh = sprintf('%s%s%s%s%s%s%s%s', h1, h2, h3, h4, h5, h6, h7, h8);
    strcmp(hstring, newh)
    Attachments:
    Matlab Script Server Test2.vi ‏40 KB

  • Get a better feedback from matlab script

    Hi everyone,
    I'm using matlab script from LabView. It seems to work, my server receives correct data but I would like to get some useful outputs. For instance, for debugging purpose, I'd like to be able to get messages sending by fprintf. And more generally, I could see if my script is crashed or running.
    Any idea?

    I "improved" my program by using as often as possible LabView to let Matlab just do the computation (LV is opening image, reading data sheet and send it as input for Matlab).
    And, as you've said, I split my big script into several one which is really better.
    Though, the main computation lasts 2min and it s a pity to wait such a long time without being sure of what's happening.
    One "solution" is to use a 'STEP' variable which is incremented along the computation under Matlab and use it as an output/indicator for LabView. So, if step didn't reach its max, it means that you can go back to debugging.
    An idea for LabView 8.0: create a kind of screen able to receive the standard output of Matlab

  • How to insert data from file into matlab script node

    I have interfaced input data from file to be processed using matlab script node. But the problem is that I could not capture the multiple data into matlab script node and to convert it into matrix. Further to this I need to process the data by plotting graphs from it. Thank you in advance for the advice

    Zarina,
    To clarify your problem, you have a script node contaning your Matlab code. Are you then using the standard LV functions to load in your data from a file and pass it into the script node?
    Regards
    Tristan

Maybe you are looking for

  • Why won't my Note 3 charge with my original wall charger?

    For the past couple of days I've been getting a notification on my phone when I plug my phone into the wall charger.  It tells me for a faster charge, use the original charger.  I am using the wall charger I received with my phone at time of purchase

  • TSV_TNEW_PAGE_ALLOC_FAILED  at SEM BCS

    Hey SAP-Admins !<p> I have a Problem with this shortdump TSV_TNEW_PAGE_ALLOC_FAILED at TA: UCWB_INT<p> We're running Windows 64 Bit /  SAP + DB with 24 GB RAM and 30 GB swap space.<p> I don't understand why we got this dump cause cause we have ZAMM a

  • Order of the iViews ?

    Hello All, I've created different roles for different applications and attached them to the Users. Now when I chk the same as a User I see this : 1. I've opened the Portal 2. I navigated thru the Roles I've been authorized-to. 3. Now all the iviews f

  • DW CS4 acting screwy now - inserted links no longer site relative...

    I'm using DW CS4 on Win 7 and it was working great for a while, but now it's going haywire. Everytime I try to use the little target icon (or any insert method other than manually typing) to link to a document it is inserting local system level full

  • I cann't add any extended attribute constraints in CACS

    Hi Support --I cann't add any extended attribute constraints in CACS. when I click the button" Add New" , it show a Dialog Box, but no selected item can appeares. the Agile4P version is 6.1.1 and oracle database is 11g Regards Terry