how to make a variable name from a string

3 次查看(过去 30 天)
2013a version
>> test='eye'
>> value = [5,5,3]
value =
5 5 3
>> eval([sprintf(test) '= data+1']);
Index exceeds matrix dimensions.
How to fix this error? Thank you for helping!

采纳的回答

kjetil87
kjetil87 2013-8-16
编辑:kjetil87 2013-8-16
The error should not appear, your code looks to work exept for the part of 'data' , should this instead be value?
test='eye';
value=[1,2,3];
eval([sprintf(test) '=value+1'])
eye =
2 3 4
The index exceeds matrix dimension could be related to that you have at some point declared a variable in your workspace ( or funciton or whatever ) with the name of eval.
try typing
which eval
it should return that eval is a built-in function, if it returns eval is a variable there is the reason for your error. If so just use
clear eval
  2 个评论
xianghong
xianghong 2013-8-19
when I tried this morning, it worked! Thank you so much! Have a great week!
Xianghong

请先登录,再进行评论。

更多回答(3 个)

Walter Roberson
Walter Roberson 2013-8-16

xianghong
xianghong 2013-8-16
This seems like to name the fields within a variable. If I just want to make a variable name from a string, how to do it? Thanks!
  1 个评论
Walter Roberson
Walter Roberson 2013-8-16
No, it is not just for creating field names within a variable. It shows a number of different alternatives to creating a variable from a string, recommending strongly that you use one of the alternatives instead of creating a variable dynamically. At the end of the FAQ it shows how to create a variable dynamically, for the rare case when you really need to do that. If you are not engaged in creating extensions to MATLAB itself, chances are that there is a better route than creating a variable dynamically.

请先登录,再进行评论。


xianghong
xianghong 2013-8-16
EDU>> test='eye';
EDU>> value=[1,2,3];
EDU>> eval([sprintf(test) '=value+1'])
Index exceeds matrix dimensions.
Looks like it still gave the error. What shall I do?
Thanks,
  2 个评论
xianghong
xianghong 2013-8-19
thank you so much! It worked this monday morning!
Have a nice day!
Xianghong

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by