how to rename a variable?
590 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a cell which contains twenty different names( Names<1x20 cell>),there is also twenty variables in my workspace like : VarName1 VarName2... I need to assign those names to these variables,the point is that I can not just overwrite them because I have values in variables and do not want to loss them.
any help would really appreciated.
0 个评论
采纳的回答
Image Analyst
2014-5-10
编辑:Image Analyst
2014-5-10
A cell cannot contain 20 different names unless the cell contains another cell, or a character array (which means all the names are the same length).
Your "Names" variable can be a 1x20 cell array - that is, an array of cells . Each cell (of the 20 cells in the array) may contain one string, or one of anything else, such as another cell, a double matrix, a structure, a table, etc. Please read the FAQ for an explanation of what cells are and how they work. http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F
Not sure why you're asking about cells at all. If you have 20 named variables like VarName1 VarName2, and so on, you can rename them and retain their data/values like this:
newVar1 = VarName1; % Copy to new variable with new and different name.
clear('VarName1'); % Delete old variable with old name.
newVar2 = VarName2;
clear('VarName2');
newVar3 = VarName3;
clear('VarName3');
and so on down to 20.
If you want those 20 separately named variables in a new cell array , with one variable in each cell, you can do this:
ca{1} = VarName1; % Copy to new variable with new and different name.
clear('VarName1'); % Delete old variable with old name.
ca{2} = VarName2;
clear('VarName2');
ca{3} = VarName3;
clear('VarName3');
4 个评论
Image Analyst
2014-5-11
This is very strongly recommended against. You should just avoid the whole situation in the first place. If you insist on ignoring recommendations, then you can use the third example in the FAQ (as Azzi referred you to yesterday):
for i=1:10
eval(sprintf('A%d = [1:i]', i));
end
This is what it would look like:
IST_WANDLER_MOM = 42; % Initialize with something
eval(sprintf('%s_newName = %s', ind2{3}, ind2{3}));
Assuming that all those variables already exist somehow, you'd do the above in a loop
for k = 1 : length(ind2)
eval(sprintf('%s_newName = %s', ind2{k}, ind2{k}));
end
At some point you'll eventually realize why it's recommended not to do that.
更多回答(3 个)
Azzi Abdelmalek
2014-5-10
Don't use several variables. Read this link http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
0 个评论
Navid
2014-5-10
4 个评论
Image Analyst
2014-5-11
Star, you need to widen the columns to get rid of the ... and see the whole string.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!