Loop through specific strcuture field names

11 views (last 30 days)
I would like to loop through specitifc feild names of my struct. At the moment the field names are typed out individually for each entry in "names" like this (variable names are more descriptive in the real code):
names={'di','da','du','bi','ba','bo','fi','fa','fu','fe'};
[R{i}.di_Beat,R{i}.di_R_med,R{i}.di_D_med,R{i}.di_R_m,...
R{i}.di_D_m]=Cut(L{i}.di_F,S_start{i},S_length{i},ts{i},1,'g');
Currently I just rewrote these two lines of code for each entry of name, this would be the next two lines for example:
[R{i}.da_Beat,R{i}.da_R_med,R{i}.da_D_med,R{i}.da_R_m,...
R{i}.da_D_m]=Cut(L{i}.da_F,S_start{i},S_length{i},ts{i},1,'g');
The field names do not appear all one after another so i can just pull out the names. I tried to concatenate teh variable names as a string unsing strcat but that did not work out. I did something along the linnes of:
for n=1:length(names)
Beat=strcat('R{i}.',names{n},'_Beat');
R_med=strcat('R{i}.',names{n},'_R_med');
D_med=strcat('R{i}.',names{n},'_D_med');
R_m=strcat('R{i}.',names{n},'_R_m');
D_m=strcat('R{i}.',names{n},'_D_m');
Signal=strcat('L{i}.',names{n},'_F');
[Beats,R_med, D_med, R_m, D_m]=Cut(Signal,S_start{i},S_length{i},ts{i},1,'g');
end
This still seems too compliocated and I am looking for an easier way to do this.
Any help is highly appreciated!
  3 Comments
SH
SH on 22 Mar 2019
Hi Stephen,
Yes I agree that putting meta-data into field names is everything else but ideal. The script itself and all functions that it is calling were written by a different person. It would be too much effort to change the entire architecture of the variables and all scripts and functions which call them, so I am just trying to improve the code in some places to make it more readable.
So taking the variable outline as a given, do you have any idea how to approach the issue above?
Thanks for your help.
Jos (10584)
Jos (10584) on 22 Mar 2019
This would only propagate badly written code ... so, my answer would be no.

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 22 Mar 2019
As Stephen says, this is going to be slow. But maybe this syntax using dynamic field names would be useful to you:
R{i}.([names{n},'_Beat'])
etc.
  1 Comment
SH
SH on 25 Mar 2019
Thank you James! That's exactly what I was looking for.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!