Create multiple substructs in loop and indexing with cellarray - matlab

Let's say I have got a struct called data and I want to create three substructs called area, inhabitants and industry. These names are stored in a cellarray.
My method looks like this:
names={'area','inhabitants','industrie'};
for i=1:length(names)
data.(names(i)) = struct;
end
I get this error: "Argument to dynamic structure reference must evaluate to a valid field name."
However doing it like this works:
somestr = 'area';
data.(somestr) = struct;
That's why I tried:
names={'area','inhabitants','industrie'};
for i=1:length(names)
somestr = names(i);
data.(somestr) = struct;
end
But I get the same error as before.
I want to do it that way because I have to import a lot of data and want to store it in Matlab. If someone later wants to change the code it might be much easier to just change the cellarray.

Until the specific element of the cell is accessed via curly braces, the element will be a one-by-one cell and not a char. So you just need curly braces:
names={'area','inhabitants','industrie'};
for i=1:length(names)
data.(names{i}) = struct;
end

Related

MATLAB: Pass part of structure field name to function

I need to pass a part of a structure's name into a function.
Examples of a available structs:
systems.system1.stats.equityCurve.relative.exFee
systems.system1.stats.equityCurve.relative.inFee
systems.system2.stats.equityCurve.relative.exFee
systems.system2.stats.equityCurve.relative.inFee
systems.system1.returns.aggregated.exFee
systems.system1.returns.aggregated.inFee
systems.system2.returns.aggregated.exFee
systems.system2.returns.aggregated.inFee
... This goes on...
Within a function, I loop through the structure as follows:
function mat = test(fNames)
feeString = {'exFee', 'inFee'};
sysNames = {'system1', 'system2'};
for n = 1 : 2
mat{n} = systems.(sysNames{n}).stats.equityCurve.relative.(feeString{n});
end
end
What I like to handle in a flexible way within the loop is the middle part, i.e. the part after systems.(sysNames{n}) and before .(feeString{n}) (compare examples).
I am now looking for a way to pass the middle part as an input argument fNames into the function. The loop should than contain something like
mat{n} = systems.(sysNames{n}).(fName).(feeString{n});
How about using a helper function such as
function rec_stru = recSA(stru, field_names)
if numel(field_names) == 1
rec_stru = stru.(field_names{1});
else
rec_stru = recSA(stru.(field_names{1}), field_names(2:end));
end
This function takes the intermediate field names as a cell array.
This would turn this statement:
mat{n} = systems.(sysNames{n}).stats.equityCurve.relative.(feeString{n});
into
mat{n} = recSA(systems.(sysNames{n}), {'stats', 'equityCurve', 'relative', feeString{n}});
The first part of the cell array could then be passed as an argument to the function.
This is one of those cases where matlab is a bit unhelpful in the documentation. There is a way to use the fieldnames function in matlab to get the list of all the fields and iterate over that using dynamic fields.
systems.system1.stats.equityCurve.relative.exFee='T'
systems.system1.stats.equityCurve.relative.inFee='E'
systems.system2.stats.equityCurve.relative.exFee='S'
systems.system2.stats.equityCurve.relative.inFee='T'
systems.system1.returns.aggregated.exFee='D'
systems.system1.returns.aggregated.inFee='A'
systems.system2.returns.aggregated.exFee='T'
systems.system2.returns.aggregated.inFee='A'
dynamicvariable=fieldnames(systems.system1)
This will return a cell matrix of the field names which you can use to iterate over.
systems.system1.(dynamicvariable{1})
ans =
equityCurve: [1x1 struct]
Ideally you would have your data structure fixed in such a way that you know how many levels of depth are in your data structure.

Matlab: iterate over multiple structs

I have 5 Matlab structs. I would like to iterate over them. My current solution is the following:
all_structs = [struct1,struct2,struct3,struct4,struct5];
for single_struct = all_structs
% do stuff to each struct here
end
However, each of the structs above has a matrix with a lot of data (including some other properties). Also, whatever I change in the single_struct is not passed back to the original struct.
Question: How do I fix that? Does Matlab copy all that data again when I create the vector all_structs? Or is the data from each of the structs (struct1,...,struct5) passed by reference? Is there a better way to iterate over multiple structs?
Thanks for helping!
struct will not be passed by reference. You will need to loop over the elements in all_structs using an index and then access and modify using that index. If you need something to be treated as reference you will need to define a class for it and make the class inherit from handle. Suggested reading
for i = 1:numel(all_structs)
% do stuff to each struct here
all_structs(i).data = ones(10,5); % your code here
end
I would suggest also reading on arrayfun, though it is useful if you want to do an operation and get results. From your description it sounds like you want to modify the structs.
In case you want to modify content of original structs, without making a copy, you can use a cell array of structs names.
Then iterate the names, and use eval to modify the content.
Using eval is inefficient, so don't make it a habit...
See the following code sample:
%Create sample structs (each struct has a data element).
struct1.data = 1;
struct2.data = 2;
struct3.data = 3;
%Create a cell array containing structs names as strings.
struct_names = {'struct1', 'struct2', 'struct3'};
%Iterate all structs names
%Modify data elements of each struct using eval.
for i = 1:length(struct_names)
sname = struct_names{i}; %Get struct name from cell array.
%Evaluate a string like: 'struct1.data = struct1.data + 1;'
eval([sname, '.data = ', sname, '.data + 1;']);
end

get struct data by name (Matlab)

Is there an easy way to get the data out of a struct by searching for his name?
I'm thinking of a struct like this:
test = struct('A', ...
[struct('Name','Adam','Data',[1 2 3]) ...
struct('Name','Eva','Data',[11 12 13])]);
Now I want to access the Data field by searching for 'Adam' or 'Eva'.
something like this:
getStructDataByName(test,'Adam')
Does someone know a script or has an idea doing this with not too much effort?
Edit:
This is my current solution:
function getDataByName(struct,fieldname)
names = getAllDataNames(struct);
thisIdx = strcmp(names,fieldname);
% or
% thisIdx = ismember(names,fieldname);
struct.A(thisIdx).Data
end
function names = getAllDataNames(struct)
for idx = 1:length(struct.A)
names(idx,:) = {struct.A(idx).Name};
end
end
Should I use strcmp() or ismember()?
Try this:
test.A(strcmp({test.A.Name}, 'Eva')).Data
Basically if you call test.A.Name it will return a comma separated list of all the names. So by putting {} around that we concatenate all those into a cell matrix. We can then use strcmp to find the indices that match the name you're after. Note that if your names can be repeated then this will return a comma separated list over all so you might want to put the curly braces around the entire expression in that case.

Accessing Matlab Struct Field with General Function

I'm trying to automate a process for getting information out of an array of structs.
I have the following code:
function [data] = extractData(struct,str)
data = {};
for i = 1:length(struct)
data{i} = struct(i).str;
end
The problem is that I want to provide the str value referring to a pre-determined field. In it's current form, it won't accept str and say "str is an unknown field."
The easiest way to do this would to use:
function data = extractData(struct)
str = fieldnames(struct);
data = {};
for i = 1:numel(str)
data{i} = struct.(str{i});
end
end
You may also want to consider a few different things here. First, you may want to change the name of your struct to a different name as was said above. Also you might want to look into cell arrays. Cell arrays can hold variables of different types and lengths and are easier you use.

Matlab dynamic fieldnames structure with cell arrays

How can i access the following structure path with dynamic fieldnames:
var = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text';
fields = textscan(var,'%s','Delimiter','.');
refxtree.(fields{:}) does not work because MaterialStreamObjects contains a cell array of which I want to access the 8th cell and then continue down the structure path.
In the end I want to get and set the fieldvalues.
You need to build the appropriate input to subsref, possibly using substruct. Look at the MATLAB help.
You can define an anonymous function to navigate this particular kind of structure of the form top.field1.field2.field3{item}.field4.field5.field6.field7 (as an aside: is it really necessary to have such a complicated structure?).
getField = #(top,fields,item)top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}).(fields{7})
setField = #(top,fields,item,val)subsasgn(top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}),struct('type','.','subs',fields{7}),val);
You use the functions by calling
fieldValue = getField(refxtree,fields,8);
setField(refxtree,fields,8,newFieldValue);
Note that fields is required to have seven elements. If you want to generalize the above, you will have to dynamically create the above functions
In this case, it is easier to just use EVAL:
str = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text';
%# get
x = eval(str)
%# set
evalc([str ' = 99']);