Storing data in an array from a for loop
1 次查看(过去 30 天)
显示 更早的评论
Hi, I want to store the array (generations) obtained in each cycle for (95 arrays). With the following code I only get the arrangement corresponding to the last loop. Any ideas how to store the obtained arrays (generations) in a single array. Thanks in advance.
num_generations = 94 ;
matrices = {};
for ii = 0:num_generations
file = sprintf('population_%d.dat', ii);
generations_fid = fopen(file, 'r');
while ~feof(generations_fid)
generations = cell2mat(textscan(generations_fid, repmat('%f', 1, (3)))); % array to store
if isempty(generations)
fgetl(generations_fid);
else
matrices{end+1} = generations;
end
end
fclose(generations_fid);
end
3 个评论
Cris LaPierre
2020-3-13
This appears to be the data once it has been loaded into MATLAB. Could you share what the dat file looks like as well? To Mohammed's point below, I'm not sure you need all the code you have, but without knowing what your data looks like, it's hard to say.
回答(1 个)
Mohammad Sami
2020-3-13
编辑:Mohammad Sami
2020-3-13
You don't need to read your file line by line. textscan can scan the entire file in one pass (unless the format spec keep changing in your file).
num_generations = 94 ;
matrices = {};
for ii = 0:num_generations
file = sprintf('population_%d.dat', ii);
generations_fid = fopen(file, 'r');
generations = cell2mat(textscan(generations_fid, repmat('%f', 1, 3))); % array to store
matrices{ii+1} = generations;
fclose(generations_fid);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!