How to replace part of variable name in loop
4 views (last 30 days)
Show older comments
I am trying to crate a code that does many simple calculations over and over again for different sets of data. My code would be on a much larger than shown, but a small example is:
DATA=xlsread('MotorData.xls',1,'A2:D50000');
for i=1:size(DATA,2)
BackMtr1Avg=mean(DATA(:,i));
BackMtr1Std=std(DATA(:,i));
BackMtr1Max=max(DATA(:,i));
BackMtr1Min=min(DATA(:,i));
end
I'd like to do these four calculations for each column in my matrix 'DATA'. However, I need to change the variable name for each column, so that for column 1 it is BackMtr1***, column 2 it is BackMtr2***, column 3 is FrontMtr1***, etc. I'm looking for a way to do this change in the variable name without explicitly writing out each variable. Something along the lines of:
DATA=xlsread('MotorData.xls',1,'A2:D50000');
names={'BackMtr1';'BackMtr2';'FrontMtr1';'FrontMtr2'};
for i=1:size(DATA,2)
string=names(1,i);
strcat(string,'Avg')=mean(DATA(:,i));
strcat(string,'Std')=std(DATA(:,i));
strcat(string,'Max')=max(DATA(:,i));
strcat(string,'Min')=min(DATA(:,i));
end
So in the end of this example, I'd have 16 separate statistical variables that are all defined without needing to explicitly define and write the 16 lines of code (in my actual program, I'm defining about 400 variables, to this would be much more useful). Obviously I know that this example wouldn't work - I'm just curious if this is even possible. Any help on this subject would be appreciated. Thank you in advance.
0 Comments
Answers (1)
Matt Fig
on 9 Jun 2011
In short, don't do it!
1 Comment
Jan
on 9 Jun 2011
@Jason: I recommend to trust this advice. We have seen several hundrets posts in the past concerning the problems arising from such approaches: A complicated method to create a pile of variables, which contain useful information in their names, demand for further complicated methods to access these varaibles again.
Use structs with the fields 'Avg', 'Std', ...
See Also
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!