General variable creation question
Show older comments
Hi,
I am still new to programming in Matlab and i tend to code in a way that generates a lot of variables in a workspace. Generally it's fine but i would like to know what my other options are to minimize workspace clutter. For an example, i am extracitng a region of interest (ROI) from some EMG data using the same start and end index, so my code snippet looks like this:
RSOL_ROI = RSOL(start_indexEMG:end_indexEMG);
RMG_ROI = RMG(start_indexEMG:end_indexEMG);
RTA_ROI = RTA(start_indexEMG:end_indexEMG);
RMH_ROI = RMH(start_indexEMG:end_indexEMG);
RVL_ROI = RVL(start_indexEMG:end_indexEMG);
RRF_ROI = RRF(start_indexEMG:end_indexEMG);
I plan to plot the _ROI variables later so i still want them stored somewhere where i can call them later. Can someone suggest a way to write code that generates the 6 _ROI variables but doesn't store them in workspace? And just for learining purposes can someone write a for loop for this as well? I have tried a few times and did not seem to work.
EDIT: I know i can place the variables into a struct. As a quick question within this question what if i have a struct with the following 6 variables stored: RSOL,RMG,RTA,RMH,RVL,and RRF. And the struct is named A. Is there a way to call the variables by direct name in my script. Basically something like X=2*RSOL. instead of having to say X=2*A.RSOL. Hope that makes sense!
Thank you for your help in advance!
Accepted Answer
More Answers (1)
John D'Errico
on 22 Mar 2023
0 votes
Don't generate a zillion variables. Instead, learn to use arrays. Cell arrays, structs, multi-dimensional arrays. This will leave you with ONE variable to chase around.
It is just a habit you need to learn as good programming practice.
3 Comments
Stephen23
on 22 Mar 2023
Or tables. The example given looks like something that could be nicely represented in a table.
Ines Shekhovtsov
on 23 Mar 2023
Stephen23
on 24 Mar 2023
One important step is to understand that meta-data (like the categories RSOL, RMG, RTA, RMH, RVL, and RRF) are data. And data belong inside variables, not in the code itself. Once you do that, then using arrays to store and process your data will be easier... and your code will be simpler and more generalizable as well.
Categories
Find more on Loops and Conditional Statements 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!