How to assign a structure name using an index?

1 visualización (últimos 30 días)
Michael Link
Michael Link el 12 de Jul. de 2017
Editada: Jan el 12 de Jul. de 2017
Hello, The problem I am having is that when I run the final line of code I receive an error message "Function 'subsindex' is not defined for values of class 'cell'." Abb is a cell array with abbreviations. I am trying to assign the structure name as the abbreviation related the filename I am interested in. Any help would be greatly appreciated.
function [GSF,DateTime,WaterGallon,WUI]=struct_construction(filename)
%%Import date and demand as a function of file name
%Using function to bring in date and demand for specific building
[DateTime,WaterGallon] = date_and_demand(filename);
%%Import building specific attributes (gross square feet, filename,
%%abbreviation, etc.) for all buildings
%Importing attributes from master sheet
[BN,Abb,FN,BuildingType,Year,GSF,Water] = import_master_sheet('Master_sheet.xlsx','Sheet1',2,239);
%%Constructing struct for each building as a function of filename
% Making Struct for Buliding and Computing Water Use Intensity
index = find(strcmp(FN, filename));
B_GSF= GSF(index);
WUI=WaterGallon./B_GSF;
WUI_avg=mean(WaterGallon);
char(Abb(index))=struct('GSF',B_GSF,'DateTime',DateTime,'WaterGallon',WaterGallon,'WUI',WUI,'WUI_avg',WUI_avg);
end

Respuesta aceptada

Jan
Jan el 12 de Jul. de 2017
Editada: Jan el 12 de Jul. de 2017
This topic is discussed almost daily. The answer is always the same: Don't do this! See http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval .
Note that char(Abb(index)) creates a string, a CHAR vector. You cannot assign a struct to a string. I can guess, what you want, but the code is written in the hope, that Matlab understands magically, that you mean the contents of teh string as a variable. This cannot work, and it should not work, because the dynamic creation of arrays causes much more problems than it solves.
Try this:
Data.(Abb{index}) = struct('GSF',B_GSF,'DateTime',DateTime, ...
'WaterGallon',WaterGallon,'WUI',WUI,'WUI_avg',WUI_avg);

Más respuestas (1)

Honglei Chen
Honglei Chen el 12 de Jul. de 2017
Here is a simple example how you can achieve that
Abb = {'file1','file2'};
temp = struct('a',3,'b',4);
index = 1;
eval([Abb{index} '=temp';])
However, using eval is in general discouraged. Have you thought about using a container.Map for this purpose? Have you thought about saving an extra field in the struct array so you can find the correct item by searching the struct array? something like
Abb = struct('name',{'file1','file2'},'a',{3 4},'b',{5 6})
Abb(cellfun(@(x)strcmp(x,'file1'),{Abb.name}))
HTH

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by