How to avoid creating 1x1 struct?
28 views (last 30 days)
Show older comments
I have created within for loop a 1x8 struct origStruct which is visual and very easy to read.
now I also have to do separately another 1x35 struct with interpolated data. Hower, all I can create is this annying 1x1 stuct with 2 fields. what i'm doing wrong?
code is:
newStruct.b = linspace(origStruct(1).b,origStruct(end).b ,35);
newStuct.e = spline(origTimeSteps,[origStruct.e],35);
and I get this which serves no purpose whatsoever since it doesent look like table:
tried code versions like:
newStruct{:}.b = linspace(origStruct(1).b,origStruct(end).b ,35);
newStruct{1:35}.b = linspace(origStruct(1).b,origStruct(end).b ,35);
newStruct.b = deal(linspace(origStruct(1).b,origStruct(end).b ,35));
but none does give proper outcome
0 Comments
Answers (1)
Stephen23
on 10 Mar 2024
Edited: Stephen23
on 10 Mar 2024
b = linspace(..);
e = spline(..);
newStruct = struct('b',num2cell(b),'e',num2cell(e));
"I get this which serves no purpose whatsoever since it doesent look like table"
Storing lots of scalar numerics in a non-scalar structure will generally make processing your data harder and less efficient than storing numeric arrays in a scalar structure. A table might be a better choice for your requirements.
2 Comments
Stephen23
on 10 Mar 2024
Edited: Stephen23
on 11 Mar 2024
"why above works but this one does not?"
Because of what you are telling MATLAB to do:
newStruct = struct; % you tell MATLAB to create a scalar structure.
newStruct.b = num2cell(..); % you tell MATLAB to create a field and store a cell array in that field.
newStruct.e = num2cell(..); % you tell MATLAB to create a field and store a cell array in that field.
There is absolutely nothing in your code (e.g. indexing, concatenation, REPMAT, etc) that would tell MATLAB to create anything other than a non-scalar structure. You explicitly told MATLAB to create a scalar structure, so that is exactly what MATLAB does.
"sometimes matlab decides that your struct will be 1x8 structs, some times it decides they are 1x1 struct where fields are 1x8 ..."
MATLAB does not decide things randomly.
"what i'm doing wrong?"
One array (e.g. that returned by LINSPACE or NUM2CELL etc.) is one array. One array is not automatically allocated to lots of separate arrays (just because you want this). MATLAB has some very specific syntaxes for allocating one array into lots of separate arrays, which you will need to use:
Here is one approach using two comma-separated lists:
new = repmat(struct,1,8);
tmp = num2cell(linspace(..));
[new.b] = tmp{:};
In general your code will be simpler and more efficient when you keep numeric data together.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!