How do I make assignments to my workspace using variable names and values in a spreadsheet?

조회 수: 2(최근 30일)
I have an excel file that has names of structures in the top row, names of fields of those structures in the 2nd row and in the remaining rows, values to be assigned to those fields in a columnwise manner. How can I read this into arrays of values for each field? Assume the values are floats.
Example: 4x4 Excel file might look like
0 1 1 2
3 2 1 2
Result should be that I have in my workspace
P.X = [0 3];
P.Y = [1 2];
V.X = [1 1];
V.Y = [2 2];
Can I do this without using eval()?

채택된 답변

per isakson
per isakson 2016년 1월 13일
편집: per isakson 2016년 1월 16일
AFAIK: one cannot do it without "eval".
Yes, there are good reasons to avoid eval. However, in your situation it might be justified to use "eval".
The code below is slightly more readable than a basic eval solution. It uses fewer blips at least. Try
cac = {
'P' 'P' 'V' 'V'
'X' 'Y' 'X' 'Y'
0 1 1 2
3 2 1 2 };
for jj = 1 : size(cac,2)
assign2struct( cac{1,jj}, cac{2,jj}, [cac{3:4,jj}] )
>> P,V
P =
Y: [1 2]
X: [0 3]
V =
X: [1 1]
Y: [2 2]
function assign2struct( name, field, value )
sas = evalin( 'caller', ['whos( ''', name, ''' );' ] );
if isempty( sas )
assignin( 'caller', name, struct(field,value) )
elseif strcmp( sas.class, 'struct' )
S = evalin( caller, name );
S.(field) = value;
assignin( 'caller', name, S )
error( '%s is not a struct', name )

추가 답변(1개)

Walter Roberson
Walter Roberson 2016년 1월 12일
편집: Walter Roberson 2016년 1월 12일
Technically you can do it without using eval(), but it would require writing a routine that used assignin('caller') to assign the value into the workspace you are already in, with much the same effect.
I recommend that you push everything down one level into a master structure, so instead of creating P.X and so on you would create (say) vars.P.X . This can be done easily using dynamic field names without the risks over eval() or of a structure name in the file accidentally being a MATLAB reserved word or accidentally being the name of a variable or function you are using in the reading routine itself. For example suppose you read your lines using fscanf() and the user has requested a structure name of 'fscanf', then as soon as you created that as a variable you would no longer be able to call the fscanf routine.
  댓글 수: 4
Walter Roberson
Walter Roberson 2016년 1월 13일
This is getting beyond what I have read about Simulink. Perhaps if you used a Model Workspace layer, and specified a .mat file that has the variables stored? A MATLAB file is also an option there but it is not obvious what form that file would have to take.

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


Find more on Programming Utilities 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