How to Create a Dynamic Variable in a function and turn it to a Global Variable to be used across scripts?
Show older comments
Hi,
I'm using MatLab to import data from LabChart in real time. The data from each block recorded is given in the global 1x3 cell gChansData and the block number is given by the global variable gLatestBlock (a number value in 1 cell only).
I know everyone says not to use eval but unfortunately I can't figure out how dynamically load the data any other way:
eval(sprintf('block_%d_data = gChansData;', gLatestBlock(1,1)))
I have written this line of code into a function which called upon by another script. The script seems to load global variables in common with the function to my current workspace, however won't load the block_%d_data dynamic variable to the workspace. I'm not sure if this is a problem with the fact it is not a global variable or just that the line of code is wrong!
Any help would be greatly appreciated, I am new to MatLab and I've been stuck for quite a few days on this!
Thanks in advance,
Sara
7 Comments
Guillaume
on 5 Mar 2017
Seriously? The two most reviled practices are probably dynamic variable names and global variables (both very hard to implement correctly, major sources of hard to track bugs and often resulting in slow code), and you want to combine them.
Double dose of badness!
Walter Roberson
on 5 Mar 2017
Stephen23
on 5 Mar 2017
@Sara Majid: what do you hope to do with dynamically named variables once they are in the workspace? Dynamically named variables are not just hard to load, they are also hard to work with. You could use a faster, easier, and simpler method (hint: indexing).
Sara Majid
on 5 Mar 2017
Sara Majid
on 5 Mar 2017
@Sara Majid: your task will be much easier with indexing. Read these:
Jan
on 6 Mar 2017
Global variables, dynamic creation using eval, writing variables to another workspace: This is a complicated programming approach, prone to errors and horrible to maintain. There must be must simpler ways.
Answers (0)
Categories
Find more on Time Series Events in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!