Dynamic structure overwrites existing fields instead of adding new field

10 visualizzazioni (ultimi 30 giorni)
I am trying to add data to a struct, where the struct is defined dynamically. I know this is bad practice and there are many posts here not to do this, but for various reasons it is the best path forward. Please believe me that this was not a haphazard idea.
I am trying to define a struct where several time series are added to a single struct. The time series are defined and named dynamically and added to the struct. I can successfully do this for one time series, but when I try to add another time series, the original one is overwritten. Simplified code below:
close all
clear
clc
A=[0 1 2 3 4 5]';
B=A*2;
Test=BuildStruct('a',[A A])
Test=BuildStruct('b',[A B])
clearvars -except Test
Function BuildStruct defined below:
function [Data]=BuildStruct(variable,data)
ts=timeseries(data(:,2),data(:,1),'Name',variable);
Data.(variable)=ts;
When I run this code, the workspace contains a structure Test with time series Test.b, but Test.a is overwritten. I want the structure Test to contain Test.a and Test.b.
Basically I am trying to output several variables, for a few different analysis cases. I don't know the case name beforehand, so I cannot explicitly define the struct name. So in my real code, I have another layer of parentheses, but this simplified version overwrites all data in the same way as the above.
I am using R2015b.
Thank you.
  1 Commento
Stephen23
Stephen23 il 20 Set 2017
Modificato: Stephen23 il 20 Set 2017
"I know this is bad practice and there are many posts here not to do this"
I can't find any such posts. Which posts state this?

Accedi per commentare.

Risposte (1)

Fangjun Jiang
Fangjun Jiang il 20 Set 2017
Modificato: Fangjun Jiang il 20 Set 2017
I think your function needs to be written in this way
function [Data]=BuildStruct(OriginStruct,variable,data)
Data=OriginStruct;
ts=timeseries(data(:,2),data(:,1),'Name',variable);
Data.(variable)=ts;
This is to address the "overwriting" issue when you create a function to build the struct. I think there is a better way to achieve your goal without creating the function, with some lines like these:
Test=struct('a',TsA,'b',TsB);
Test=setfield(Test,'c',TsC);
  1 Commento
Fangjun Jiang
Fangjun Jiang il 20 Set 2017
Well, Data.(variable)=ts is the same as Data=setfield(Data,variable,ts). Looking back, I think your BuidStruct() function is basically the same as the built-in function setfield()
ts=timeseries(data(:,2),data(:,1),'Name',variable);
Data=setfield(Data,variable,ts);

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by