MATLAB Answers

Concatenate variable value and variable name into new variable name.

322 views (last 30 days)
I would like to have the name of a variable into another variable name.
So if for example I define
animal = 'cat' and make some calculation: eg. mean. I would like a variable name which concatenates these two: 'cat_mean'.
So if swap to animal = 'dog' there will be created another variable named 'dog_mean'
Best regards Jesper

  0 Comments

Sign in to comment.

Accepted Answer

Adam
Adam on 5 Apr 2016
Edited: Adam on 5 Apr 2016
Why would you want to do this though? A variable name is just a handle used in code. Suppose you create these dynamic variable names. Now everywhere afterwards in the code you have to keep working with these and using ugly code constructs to do so because you can't just refer to a variable properly by its name in the code.
Just use a struct if you want to do something like this e.g.
cat.mean = ...
dog.mean = ...
or if you only want one variable rather than separate ones for cat, dog, etc
animal.type = cat;
animal.mean = ...
animal(2).type = 'dog'
animal(2).mean = ...

  3 Comments

Jesper Steen Andersen
Jesper Steen Andersen on 6 Apr 2016
Thank you for your reply.
First of all, because I am beginner at MATLAB and I do not know how else to get my problem fixed. I have various folders containing csv-files with data calculated for a lot of files. The folders are named depending on what aspect (feature) of files is calculated. In the first part of my script I define this feature-variable and I use 'strcat' to construct the filenames that I read into MATLAB via "csvread".
In the next part I calculate different sorts of statistical properties of each files (mean, median, std). At the moment, it would be convenient to name these statistical properties so that I know what 'feature' they were calculated for. And I thought that renaming them was a way to do it. But there might be much better ways?
Adam
Adam on 6 Apr 2016
Well, basically using structs as above
doc struct
will help give you the equivalent flexibility in naming whilst still allowing you to access these variables easily.
For example, you can do with struct fields what you cannot easily do with variable names - i.e. use a dynamic string to access into them e.g.
feature = 'someFeature';
myStruct.( feature ) = featureVal;
This will create a field on your structure as
myStruct.someFeature
in the same way as if you had just hard-coded that, but allowing you to have read that string dynamically from, for example, a filename.

Sign in to comment.

More Answers (2)

Orion
Orion on 5 Apr 2016
Hi,
something like :
animal = 'cat';
operation = 'mean';
result = horzcat(animal,'_',operation)

  0 Comments

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 5 Apr 2016
Edited: Azzi Abdelmalek on 5 Apr 2016
animal = 'cat'
out=sprintf('%s_mean',animal)

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by