Dynamic variables in loop
古いコメントを表示
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
採用された回答
その他の回答 (2 件)
Steven Lord
2018 年 7 月 10 日
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 件のコメント
J S
2018 年 7 月 10 日
Steven Lord
2018 年 7 月 10 日
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".
カテゴリ
ヘルプ センター および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!