Dynamic structure overwrites existing fields instead of adding new field

10 ビュー (過去 30 日間)
Josh
Josh 2017 年 9 月 20 日
編集済み: Stephen23 2017 年 9 月 20 日
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 件のコメント
Stephen23
Stephen23 2017 年 9 月 20 日
編集済み: Stephen23 2017 年 9 月 20 日
"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?

サインインしてコメントする。

回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2017 年 9 月 20 日
編集済み: Fangjun Jiang 2017 年 9 月 20 日
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 件のコメント
Fangjun Jiang
Fangjun Jiang 2017 年 9 月 20 日
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);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by