필터 지우기
필터 지우기

Interchange variable names and strings

조회 수: 2 (최근 30일)
Timothy Cale
Timothy Cale 2012년 2월 21일
편집: Asl 2013년 10월 21일
How do I convert a string to a variable name (and vice versa)?
I want to read in a string, and use it as a variable name, such as when I load a *.mat, in which the variable names depend upon which program generated/saved the *.mat.
I can see it useful to convert a variable name to a string.

채택된 답변

Walter Roberson
Walter Roberson 2012년 2월 21일
<http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Consider using
S = load('YourMATFile.mat');
the_var_names = fieldnames(S);
second_var = S.(the_var_names{2});
You can slice, dice, trice, even julienne!
  댓글 수: 2
Timothy Cale
Timothy Cale 2012년 2월 23일
Walter:
Thanks, your suggestion can be used to do what I need; i.e., to be able to load saved *.mat data into a program for which the variable names differ from those used in the saving program.
I use the form:
save('name','var1','var2' . . . . )
And as long as var1 is a variable name in the loading program, all is good.
What I "really" want to do is let the loading program read the names of the variables used in the saving program . . . But I can use the order of storage, as you suggest.
Walter Roberson
Walter Roberson 2012년 2월 23일
the_var_names in the above code would contain the variable names.
I just pulled out the second one as an example to show how you can get at the data.

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

추가 답변 (1개)

Doug Hull
Doug Hull 2012년 2월 21일
We need more details on what you are doing, but this is likely a bad idea. Your code is going to be very difficult to write like this, and you will be fighting MATLAB along the way quite a bit.
There are probably better ways of doing this than allowing users to define the internal variable names to your program. You would need to validate the names, write your code to handle unknown variable names, etc. There is likely a better way.
  댓글 수: 1
Timothy Cale
Timothy Cale 2012년 2월 23일
Doug:
I got an answer which I can use for now from Walter Robeson. My comment to him explains more about what I want to do . . .
Thanks,
Tim

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

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by