How do I create variable names from string variables

조회 수: 10(최근 30일)
If I have 2 variables, ID has a column of strings like 'height' or 'speed', data has a column of corresponding variables.
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.
height = 10;10;7
speed = 2.4;2.1

채택된 답변

Matt Kindig
Matt Kindig 2013년 8월 12일
편집: Matt Kindig 2013년 8월 12일
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
vars.height; %height variables
vars.speed; %speed variables
  댓글 수: 2
Matt Kindig
Matt Kindig 2013년 8월 12일
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.

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

추가 답변(1개)

Andrei Bobrov
Andrei Bobrov 2013년 8월 13일
편집: Andrei Bobrov 2013년 8월 13일
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
Matt Kindig
Matt Kindig 2013년 8월 15일
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.

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


Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by