Loop only the first execution

7 views (last 30 days)
Me29
Me29 on 17 Nov 2016
Commented: Walter Roberson on 17 Nov 2016
Hello,
I am trying to create a loop in a GUI that only loops the first time the program is run through, and then skip that portion any other time it comes to it. How can I do this?
This is the code I need in the loop to execute only the first time:
connection = tcpip('127.0.0.1', 3333, 'NetworkRole', 'server'); % connect to server socket via TCP/IP
fclose(connection);%Make sure socket is closed before attempting to open port
fopen(connection);
Thanks in advance for any help!
SM

Answers (1)

Walter Roberson
Walter Roberson on 17 Nov 2016
persistent has_been_initialized
if isempty(has_been_initialized)
connection = tcpip('127.0.0.1', 3333, 'NetworkRole', 'server'); % connect to server socket via TCP/IP
fclose(connection);%Make sure socket is closed before attempting to open port
fopen(connection);
has_been_initialized = true;
end
Reminder: your variable connection looks like a local variable in the workspace of that function. If that local variable goes out of scope then the connection will be shut down.
  2 Comments
Me29
Me29 on 17 Nov 2016
Ok. I am using this in a GUI. I don't want it to close when it goes out of that function. How can I setup connection outside of the function but still be in the GUI? I tried making it global inside the GUI and it crashed my program. Basically I want to connect and loop while connected, and do some tcpread/write while looping, depending on which button is pressed. How can I do that?
Thanks for the help,
SM
Walter Roberson
Walter Roberson on 17 Nov 2016
See the above link on the various ways you can export information from a function.
One way would just be
persistent connection
if isempty(connection)
connection = tcpip('127.0.0.1', 3333, 'NetworkRole', 'server'); % connect to server socket via TCP/IP
fclose(connection);%Make sure socket is closed before attempting to open port
fopen(connection);
end

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!