Renaming cells inside structure from variable in for loop

I have a for loop which it goes through mat files and copy results to put them inside one structure called (level0). This structure has many cells based on the number of the files (e.g 10) and I want to rename them based on variables (dates).
in other words that each cell or fields will have the name with the date and it has inside a structure with these values
dir = 'directory';
filePattern3 = fullfile(dir, 'x*.mat');
mat3 = dir(filePattern3);
name3= {mat3.name}.';
numfiles3 = length(name3);
results3 = cell(numfiles3,1);
dates = [cellfun( @(S) datetime(S([3:9]), 'InputFormat', 'yyMMMdd'), name3, 'uniformoutput',false )];
dates = [cellfun(@datestr,dates,'un',0)];
for K = 1 : numfiles3
thisfile3 = name3{K};
datastruct = load(thisfile3);
xval = [datastruct.x_.coorx.val].'; %extract variable
yval = [datastruct.x_.coory.val].';
zval = [datastruct.x_.coorz.val].';
mjd = [datastruct.x_.coorx.mjd].';
t = mjd / 365.2425;
level0{K}.xval = xval;
level0{K}.yval = yval;
level0{K}.zval = zval;
level0{K}.t = t;
end
Please help me to achieve that, thanks in advance
The dates are
dates =
'04-Apr-2002'
'11-Apr-2002'
'18-Apr-2002'
'25-Apr-2002'
'25-Apr-2002'
'01-Aug-2002'
'08-Aug-2002'
'15-Aug-2002'
'22-Aug-2002'
'29-Aug-2002'

댓글 수: 5

Do not do this! It is the contents of a variable that should be able to change, not its name.
You are way better of storing the date in a field of the structure.
is there a way to achieve that ? because later I would call these values from each cell inside structure to use them for further computations .
"because later I would call these values from each cell inside structure to use them for further computations "
Indexing is best. Fieldnames if you really must.
Can you please share similar example for indexing? I am still beginner with these stuff.
Thank you

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2019년 1월 24일
편집: Stephen23 2019년 1월 24일

1 개 추천

You can certainly rename fields dynamically:
But really, it would likely be simpler and more efficient to use indexing and store the dates as data in their own right. Forcing meta-data (such as dates) into things like variable names or fieldnames just makes code slow and fragile. Remember that meta-data is data, and so it deserves to be treated as data and stored in a variable, not forced awkwardly into names of variables or fields:
S(k).X = [...];
S(k).Y = [...];
S(k).date = '2019-01-24';

카테고리

도움말 센터File Exchange에서 Calendar에 대해 자세히 알아보기

제품

릴리스

R2016a

질문:

2019년 1월 24일

댓글:

2019년 1월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by