Dynamic variables in loop
Afficher commentaires plus anciens
Hey there,
I got some string data and want to plot the amount of chips of N amount of players (<15).
I tried dynamic variables (I know they shouldn't really be used) and similar methods but cannot get it to work after quite some time spend on it.
Basically I want to store all the data with sth like 'index_chips.playercount' and 'chips.playercount' instead of computing it manually with 'index_chips1' 'index_chips2' 'index_chips3' and so on.
for i=1:playercount %N amount of players
index_chips1 = strmatch('1:', text)+4;
chips1= str2double(text(index_chips1,1));
chips1= num2cell(chips1);
chips1(cellfun(@(chips1) any(isnan(chips1)),chips1)) = [];
chips1=cell2mat(chips1);
plot(chips1)
hold on
end
This term (gives me loads of trouble):
'1:'
also needs to be instead (the colon needs to be after the playercount)
'playercount:'
Thanks a lot for any suggestions
Réponse acceptée
Plus de réponses (2)
Steven Lord
le 10 Juil 2018
Don't create variables named like that.
numPlayers = 10;
chipCounts = randi([1 100], 1, numPlayers)
Now when you want the chip count for player 7 (for example) it's easy.
chipCounts(7)
Plotting chip counts? Also easy.
figure
subplot(3, 1, 1)
plot(chipCounts)
title('Line plot');
subplot(3, 1, 2);
bar(chipCounts)
title('Bar chart');
subplot(3, 1, 3)
pie(chipCounts)
title('Anyone for pie?');
2 commentaires
J S
le 10 Juil 2018
Steven Lord
le 10 Juil 2018
Don't create one variable per player. I would create a struct with one field per player and store vectors in those fields (you can use dynamic field names to refer to the field if you have a char vector containing the name of the field) or a table array with one table variable per player.
Creating variables with dynamic names can be slow and can lead to Bobby Tables syndrome or "poofing".
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!