How do I create variable names from string variables
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
If I have 2 variables, ID has a column of strings like 'height' or 'speed', data has a column of corresponding variables.
ie
ID = 'height' 'height' 'height' 'speed' 'speed'
data = 10;10;7;2.4;2.1
How do I create the variable 'height' and a variable speed with the corresponding data.
ie
height = 10;10;7
speed = 2.4;2.1
0 comentarios
Respuesta aceptada
Matt Kindig
el 12 de Ag. de 2013
Editada: Matt Kindig
el 12 de Ag. de 2013
If you can, avoid doing this. This explains why: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Instead, make them fields of a structure. You can do something like this:
vars = struct(); %structure to hold your variables
ID = {'height' 'height' 'height' 'speed' 'speed'};
data = [10;10;7;2.4;2.1];
fields = unique(ID); %get variable names as field names
for k=1:length(fields), %for each unique variable
fld= fields{k}; %field name
tf = ismember(ID, fld); %which corresponding data
vars.(fld) = data(tf); %assign to field
end
vars.height; %height variables
vars.speed; %speed variables
2 comentarios
Matt Kindig
el 12 de Ag. de 2013
How do you mean? Do you have an additional field in 'ID' that is called 'date' or similar? I wrote this code to be extensible to an arbitrary set of fields, so I think that additional ID elements (with corresponding values in 'data') should work fine.
Más respuestas (1)
Andrei Bobrov
el 13 de Ag. de 2013
Editada: Andrei Bobrov
el 13 de Ag. de 2013
ID = {'height' 'height' 'height' 'speed' 'speed'};
data = [10;10;7;2.4;2.1];
[i0,i1,i1] = unique(ID);
vars = cell2struct(accumarray(i1(:),data(:),[],@(x){x}),i0,1);
1 comentario
Matt Kindig
el 15 de Ag. de 2013
I should have figured there was an easy way to do this using accumarray. Try as I might, I still can't get the hang of that function.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!