How to Create a Dynamic Variable in a function and turn it to a Global Variable to be used across scripts?

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

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!
@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).
@Walter Roberson - I'm using the matlab sampling .m file provided in the labchart start menu, but thank you for the link I'm looking into it now
@Stephen Cobeldick I'm going to load the data within each variable into one table so that I can plot and manipulate the data - I know very little about matlab so will look into indexing now thank you
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.

Sign in to comment.

Answers (0)

Asked:

on 5 Mar 2017

Commented:

Jan
on 6 Mar 2017

Community Treasure Hunt

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

Start Hunting!