How can I name variables in a for loop?

I've got a skript loocking like this:
stn1=['11';'19';'27';'35';'43';'52'];
day1=['06';'06';'07';'07';'08';'09'];
for ic=1:size(stn1,1)
data=load([path,'SBE19plus_01904746_2016_09_',day1(ic,:),'_00',stn1(ic,:),'.asc']);
S=data(:,5);
T=data(:,7);
end
Loading the data goes fine, but I whant S and T to be saved as ex. S1, T1, S2, T2 etc. for every time the loop goes. Do you have any idea of how to do this? Right now I only get the last datafile on my S and T, e.g all previous data is gone when le loop is finished.

3 commentaires

Stephen23
Stephen23 le 20 Sep 2016
Modifié(e) : Stephen23 le 20 Sep 2016
Don't do this! Naming variables dynamically is possible, but it is slow, buggy, makes code very difficult to debug, and removes lots of useful code checking and code writing tools that MATLAB provides to make your life easier. Fast, efficient code uses indexing and few variables. Read this to know more:
Learn to use cell arrays, structures, indexing, and multi-dimensional arrays... then you learn how to write neat and efficient MATLAB code:
Don't do this for the reasons already explained. It seems fast and easy at first to do this, but it is a very bad idea and will cause you a lot of problems later on. As Adam pointed out Cell Arrays are probably the way to go.
If for any reason you (think) you need to do it, try combining eval and sprintf
i = 1;
eval(sprintf('A%d = rand(10,1);', i));

Connectez-vous pour commenter.

Réponses (1)

Adam
Adam le 20 Sep 2016
Modifié(e) : Adam le 20 Sep 2016
Use a cell array:
S{i} = data(:,5);
T{i} = data(:,7);
You really don't want all those individually named variables. Matlab is built around using arrays, not millions of individual variables.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Commenté :

le 20 Sep 2016

Community Treasure Hunt

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

Start Hunting!

Translated by