Accessing to Variables with Incremental Names in a Loop

1 Ansicht (letzte 30 Tage)
Berk Kucukoglu
Berk Kucukoglu am 11 Apr. 2019
Kommentiert: Berk Kucukoglu am 18 Apr. 2021
Hello,
In my workspace, I have the data structures:
stream1 (1x1 struct)
stream2 (1x1 struct)
...
streamN (1x1 struct)
I would like to create a master struct, merging all of these. I thought of using a "for loop" for this job.
I have also read some other questions, having extremely similar topics. In all of those questions, the asker was warned about not using this kind of "dynamic variable naming" kind of stuff. People wrote lines and lines of text telling how bad of a practice it is.
However,
I need to do this. The device I own gives data in this form - in the form of streams. There is no way I can merge them one by one. I need to reach them in a loop.
Hence my question is:
How to do this? Or, is there any other way to do this?
Thanks,
Berk
  4 Kommentare
Stephen23
Stephen23 am 11 Apr. 2019
"I need to do this."
I doubt that.
"The device I own gives data in this form - in the form of streams."
Sure. But you forgot to tell us the one vital piece of information which would let us actually help you: how did this data get into the MATLAB workspace? Most likely you did not sit and write all of those variable names out by hand, which means that you likely imported that data from file/s, or the data was generated by some badly written third-party code. In either case, that is where you should fix your code: at the source of the problem, not by dynamically accessing variable names.
For example you might be able to avoid the whole thing by simply loading into an output variable:
S = load(...)
and accessing the fields.But it depends on how that data gets into the MATLAB workspace which you have forgotten to tell us anything about.
Berk Kucukoglu
Berk Kucukoglu am 18 Apr. 2021
Hello. Sorry for the (huge) delay. I thank you for your answer.
I went with the "avoid the whole thing" route.
Thank you all for your answers.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 11 Apr. 2019
Bearbeitet: Matt J am 11 Apr. 2019
streamAll = arrayfun(@(i) evalin('caller',['stream', num2str(i)]) , 1:N )
  1 Kommentar
Berk Kucukoglu
Berk Kucukoglu am 18 Apr. 2021
Wow, this is also an interesting solution.
I tried to avoid this completely. Yet if I could not find a way to avoid it completely, I would definately have used this.
Thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by