How to rename a variable with a char

In my work space i have a variable that i'd like to rename, with a name that is held as a char.
I want to do this in a simple m file which I can run whenever required.
I have some code that works
%where label name is my newname and DataCopy is my variable
str = [Label_name,'= DataCopy;'];
eval(str);
But I keep reading not to use the eval command, i don't know why and frankly i don't care. What i do know is it works ok from the command but crashes when run in my program.
I would just like to find a way of doing this simple repeated task.
I've tried a few other options but just seem to end up putting the string into the data and not renaming!

9 Comments

and frankly i don't care
Then your question is a bit puzzling. If you don't care that you shouldn't be using eval then why don't you?
Adam
Adam on 20 Sep 2018
Edited: Adam on 20 Sep 2018
It's hard to understand what context would cause someone to feel the need to repeatedly dynamically change a variable name so, given no information on what exactly goes wrong it is not really worth trying to suggest anything. If you are really set on doing this and keeping a variable rather than a field of a struct then possibly eval is the only method, but again, you give no information on what/why/how it 'doesn't work'.
"... i come on here all i see are sarcastic unhelpful comments, so id idnt relly need a lecture on why not to use it."
We want to help, but you don't want a lecture or an explanation... hmm...
Some like to be sarcastic and then provide helpful codes. Some just like to help without sarcasm. It depends on how tempting the post is to open up sarcasm, which ironically, your post does perfectly! Watch:
"I have some code that works" ... "What i do know is it works ok from the command but crashes when run in my program."
So no, you do not have a reliable, working code. Especially since an eval is used, which is known to cause issues like this. Show us the code.
"..it cant be that difficult to rename a variable, can it. well reading some of the threads on here it obviously is!"
If you read the threads, many of them DO provide the solution to your problem! The problem is, these answer are too correct because they avoid using eval. How unfortunate, as we do need more non-ideal answers like this:
str = [Label_name,'= DataCopy;'];
try
eval(str)
catch
error('Something is definitely wrong with this eval approach: %s', str).
end
In rare cases, eval is an okay "quick" fix, but it's very hard for us to determine what kind of situation warrants the use of eval. Let us know what your situation is.
Our question to you is, are you willing to risk taking some criticism to get a better code that works and fixes your problem? I once got scolded by the MVPs here for suggesting an eval answer, oops, but that's part of learning.
Upload your code and the fix might be easier than you imagine.
Why do you want to do this? Let's assume you can do this, how are you going to access this variable later on in your code?
I'll rephrase the question it's actually an array containing some data
lets say ArrayOld [0.05, 0.3, 0.7]
i have a char called Label_Name that contains the string 'ArrayNew'
I want to rename ArrayOld to ArrayNew
so i end up with ArrayNew[0.05, 0.3, 0.7]
In the workspace it's easy you can create a copy of an array then right click and rename it, trying to do this in m file script doesn't seem straight forward
How are you generating ArrayOld? via a load command, or by some other command?
And what do you want to do with ArrayNew? resave it to a mat file, or compute something?
I expect there is a simpler way to do what i want. There is a file that someone else has produced so i dont relly want to go into taking their code apart, the output is a struct which contains fields and values.
I want each of these arrays saved into a mat file not within the stuct. Each array is then used in a matlab simulink model.
I was going to put code in the file that copied and renamed the array.
Adam
Adam on 20 Sep 2018
Edited: Adam on 20 Sep 2018
Working with struct fields it is very easy:
myStruct.( Label_Name ) = ArrayOld;
Then you can save these to a mat file still as individual variables e.g.
save( 'somefilename.mat', '-struct', 'myStruct' )
Then you can load the variables into a different session or workspace, ideally loaded as a struct then referred to again via dynamic string field names if needed, but if you really want you can load them straight into your new workspace as variables and work with them in whatever way you choose.
When it comes to loading in data in a Mat file it always involves things with potentially unknown names arriving in the workspace, whether they are field names or variables names so as long as your code knows what it is expecting then it should work.
Thank you this works. It's what i was hoping for two easy lines of code that fit into the existing program without breaking anything. Nice :-)

Sign in to comment.

Answers (2)

This bad code works either from the command line or in a script, though no competent MATLAB programmer in the world would recommend it (not even me):
Label_name = input('Enter the variable name : ', 's')
DataCopy = rand(2)
str = [Label_name,'= DataCopy;']
eval(str)
% At this point we have no idea what the variable is called,
% unless we pull some tricks with whos()
% which I'm not going to go into.
% But we'll assume you typed in "unwise"
% so let's look as the properties of a variable called unwise.
whos unwise
unwise
% IMPORTANT NOTE: Like Jos said, if you don't know what the string is,
% then how will you use it later in your code?

2 Comments

i'm not a competent matlab programmer, my work involves building simulink model i rarely have to go into the code. I saw the example using eval, and i also see lots of comments saying not to use it i tried it in the m file that i didnt write, and it crashed. I just want to rename the arrays in a script so i can use them in my model, something i can do easily in the workspace window. Obviously renaming the 50 odd arrays manually would be quicker than getting a straight answer from here!
quicker than getting a straight answer from here!
You're complaining about getting sarcam yet your comment and question appear very antagonistic.
You've had a very straight answer by Image Analyst. The answer he's written works and is the simplest way to rename the variable using eval. So, if it doesn't work for you, that's because either you're doing it wrong, or what you're trying to achieve is not what you've described. Either way, you can't complain that you're not getting the right answer if you're not describing the problem properly.
and it crashed
What does that mean? Crash normally means that matlab terminates and thus that you've encountered a serious bug. Perhaps, you mean it errors (completely different meaning!) in which case, you're not helping us by not giving us the error message.
Obviously renaming the 50 odd arrays manually would be quicker
Even faster would be to not rename the variables at all and continue using the names they already have. You say you don't want to discuss this, but this is the approach we would naturally take. Perhaps, your use case is special, but if you don't explain it, we can't understand what needs doing.
Disclaimer: No sarcasm was intended in this post.

Sign in to comment.

"the output is a struct which contains fields and values."
S = otherPersonFunction(...); %Returns structure with fields and values
"I want each of these arrays saved into a mat file" Do you want it to be saved as "NewArray"?
Fields = fieldnames(S);
for f = 1:length(Fields)
NewArray = S.(Fields{f});
save(sprintf('%d.mat', f), 'NewArray'); %You'll generate 1.mat, 2.mat, etc each storing a NewArray variable
end
"Each array is then used in a matlab simulink model."
Temp = load('l.mat', 'NewArray');
NewArray = Temp.NewArray;
or just
load('1.mat') %will poof NewArray into the workspace - not recommended

Products

Release

R2011b

Asked:

on 20 Sep 2018

Commented:

on 21 Sep 2018

Community Treasure Hunt

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

Start Hunting!