I have defined the struct written down.
SATS_Hour = struct('SATS_H0',[],'SATS_H1',[],'SATS_H2',[],'SATS_H3',[],...
'SATS_H4',[],'SATS_H5',[],'SATS_H6',[],'SATS_H7',[],...
'SATS_H8',[],'SATS_H9',[],'SATS_H10',[],'SATS_H11',[],...
'SATS_H12',[],'SATS_H13',[],'SATS_H14',[],'SATS_H15',[],...
'SATS_H16',[],'SATS_H17',[],'SATS_H18',[],'SATS_H19',[],...
'SATS_H20',[],'SATS_H21',[],'SATS_H22',[],'SATS_H23',[]);
I have to access a struct to write on each individual SATS_Hour.SATS_H0 for the first time of my loop, it contains 48 loops. The number after the letter H, of each variable, must change up to the last one 47.
How can I do this?
Using fprintf or other Matlab command?
Thanks for the help.
Gilberto Fernandes

 채택된 답변

Guillaume
Guillaume 2018년 2월 15일
편집: Guillaume 2018년 2월 15일

0 개 추천

Numbering variables or structure fields is a bad idea. Any time you start naming things sequentially you need to think of using an array instead. Here, for example you'd be better off using a cell array. I.e use:
SATS_Hour = cell(23, 1); %instead of a structure
for idx = 1:23
SATS_Hour{idx} = ...
end
Indexing is always easier than awkward name construction via sprintf. If you're hell bent on using a structure:
for idx = 1:23
SATS_Hour.(sprintf('SATS_H%d', idx)) = ...
end
As you see, it's more complicated, less readable, and probably slower.

댓글 수: 4

Gilberto Santos
Gilberto Santos 2018년 2월 15일
편집: Gilberto Santos 2018년 2월 15일
The size of each fields in cell´s case may be different?
Guillaume
Guillaume 2018년 2월 15일
Behing the scenes, cell arrays and structures are identical. The only difference is that you access each element of a cell by indexing whereas for a structure it's by its name.
Each element of a cell array can be different size and type. Same as for a structure.
Stephen23
Stephen23 2018년 2월 15일
편집: Stephen23 2018년 2월 15일
"If you're hell bent on using a structure" use a non-scalar structure:
for k = 1:23
SATS_Hour(k).SATS_H = ...
end
Guillaume
Guillaume 2018년 2월 16일
I don't see how a structure array with just one field is any better than a cell array. Seems to add a level of indirection for no reason.

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

추가 답변 (2개)

Gilberto Santos
Gilberto Santos 2018년 2월 15일

0 개 추천

Thanks a lot. I am running the main program when it finishes I will run the function with your code suggestion.
I will keep you informed ASAP.
Best Regards,
Gilberto Fernandes
Gilberto Santos
Gilberto Santos 2018년 2월 16일

0 개 추천

Thanks you All. It worked. I have accepted the advice of using a cell array.
Best Regards to All,
Gilberto Fernandes

질문:

2018년 2월 15일

댓글:

2018년 2월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by