Dynamic structure overwrites existing fields instead of adding new field
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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
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 Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!