필터 지우기
필터 지우기

Dynamic structure overwrites existing fields instead of adding new field

조회 수: 27 (최근 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by