Effacer les filtres
Effacer les filtres

Dynamic structure overwrites existing fields instead of adding new field

19 vues (au cours des 30 derniers jours)
Josh
Josh le 20 Sep 2017
Modifié(e) : Stephen23 le 20 Sep 2017
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 commentaire
Stephen23
Stephen23 le 20 Sep 2017
Modifié(e) : Stephen23 le 20 Sep 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?

Connectez-vous pour commenter.

Réponses (1)

Fangjun Jiang
Fangjun Jiang le 20 Sep 2017
Modifié(e) : Fangjun Jiang le 20 Sep 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 commentaire
Fangjun Jiang
Fangjun Jiang le 20 Sep 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);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by