How do I create variable names based on string values in an excel workbook and assign values to each variable with data in the workbook

조회 수: 2 (최근 30일)
I have an excel workbook that has names in column 1 numbers in column 2 and a variation of numbers in columns 3 through 15. I am trying to create variables with names equal to the string values in column 1 concatenated with the numbers in column 2 and assign the number values in columns 3 through 15 in each row to the respective variable created from that row. Also, I have some columns(3:15) in certain rows that do not contain any values. I have attached a sample excel document and the code that I have so far is
[num, txt, raw] = xlsread('sampleData.xls','Year2016');
fclose('all');
[rows columns] = size(raw);
names = raw(2:rows,2); % my data contains headers that I do not care about
nameNumber = num2str(num(2:rows,1)); % I have duplicate names and need to distinguish them
nameAndNumber = genvarname(strcat(names, '_Number_', nameNumber, '_2016'));
that all works but then I do not know how to assign the data to each variable. Everything I have tried has not worked. The end product would be variables that look something like this
Peter_Number_1_2016 =
164 144 153 167 164 158
Jason_Number_1_2016 =
157 160 183 175 164
Jason_Number_2_2016 =
153 165 193 155 201 78 72
and so on
  댓글 수: 2
Stephen23
Stephen23 2016년 12월 14일
편집: Stephen23 2016년 12월 14일
@Terrence Jenkins: learn why it is a really bad idea to create variable names dynamically:
As Adam's answer states, a much better solution is to use structures. Alternatively you can learn how to use indexing.
Terrence Jenkins
Terrence Jenkins 2016년 12월 15일
I have no issue using structures, so I can get this to work for 1 and by using Adam's code in a for loop and changing fieldname line to fieldname(i,1) = stuff; I can generate the list of concatenated names but s.fieldname = morestuff only generates 1 line of variable contents and using s.fieldname(i,1) = morestuff I get the error "Subscripted assignment dimension mismatch.

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

채택된 답변

Adam
Adam 2016년 12월 14일
Just use struct fields instead. This is ghastly to do with variables, but you can create a struct field from a string easily, e.g.:
n = 2;
name = 'Fred';
fieldName = [ name num2str(n) ];
s.( fieldName ) = 3;
  댓글 수: 4
Terrence Jenkins
Terrence Jenkins 2016년 12월 16일
I figured out what I was doing wrong and got it to work with your answer, thank you.
Image Analyst
Image Analyst 2016년 12월 16일
Hopefully you'll reconsider if I also say I think it's not a good idea. So now, Stephen, Adam, and I all think it's not wise or best to do that (even if it's technically possible), and I'm sure others think likewise.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by