Concatenate variable value and variable name into new variable name.

조회 수: 180(최근 30일)
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

채택된 답변

Adam 2016년 4월 5일
편집: Adam 2016년 4월 5일
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
Jesper Steen Andersen
Jesper Steen Andersen 2016년 4월 6일
Perfect! This helped me. Thanks a lot!

댓글을 달려면 로그인하십시오.

추가 답변(2개)

Orion 2016년 4월 5일
something like :
animal = 'cat';
operation = 'mean';
result = horzcat(animal,'_',operation)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 4월 5일
편집: Azzi Abdelmalek 2016년 4월 5일
animal = 'cat'


Find more on Animation 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!

Translated by