how can i assign a variable existing in the workspace to a char ?

3 visualizaciones (últimos 30 días)
Hello everyone,
how can i assign a variable existing in the workspace to a char ?
For example, in my workspace i have: label = 1 (double)
in a script i have a variable X = 'label' (char), so i want it to take the value of the variable label so that X = label = 1.
Is it possible to do such thing ?
Thanks alot for your help

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 26 de Feb. de 2019
Editada: Fangjun Jiang el 26 de Feb. de 2019
label=1;
X='label';
y=evalin('base',X);
And wait for comments critizing this method.
  2 comentarios
Jan
Jan el 27 de Feb. de 2019
Here are the expected comments, which critize this method: Don't do this, because it increases the complexity of the code even further. See TUTORIAL: How and why to avoid Eval
:-)
Fangjun Jiang
Fangjun Jiang el 27 de Feb. de 2019
Ok, let's do it the right way. Assume the following data in an Excel file. Use table so any value can be referenced by T{X,Y}
name value threshold
label1 1 10
label2 2 20
label3 3 30
T=readtable('book1.xlsx','ReadRowNames',true)
X='label2';
Y='threshold';
T{X,Y}

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 26 de Feb. de 2019
Use a struct and dynamic field names:
% In the current workspace:
Data.label = 1;
Result = YourFunction(Data);
function Result = YourFunction(Data)
Field = 'label';
Result = (Data.(Field) + 1) ^ 2;
end
Remember, that it is a DON'T to access variables dynamically: See TUTORIAL: How and why to avoid Eval
But fieldnames are efficient and clean.
  5 comentarios
Jan
Jan el 26 de Feb. de 2019
@Daher: "I managed to extract all the variables into my workspace" - I assume the problem is here. It would be much easier to import the strings as a list and the data as a matrix. Then the access is easy: with the strcmp you find the corresponding row directly.
Fangjun Jiang's idea hits the point also: With importing the data as a table object, the access of the named rows is trivial also. Importing the data as a struct is equivalent, but more handmade.
Daher
Daher el 27 de Feb. de 2019
Hello guys,
thanks again for your replies,
@Fangjun Jian : i see no difference using these commands as i use xlsread ...
Anyway, the evalin command works fine for my case so i think i'll use it.
Thanks for the help guys !

Iniciar sesión para comentar.

Categorías

Más información sobre Axis Labels en Help Center y File Exchange.

Productos


Versión

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by