Storing data in an array from a for loop

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
Cris LaPierre 2020년 3월 13일
Do all 95 arrays have the same number of columns? It would also be helpful if you could share a sample of the data file.
Thanks for your reply. Yes, they have the same number of columns, 3. This is a sample.
Thanks.
generations =
-2.7770 -4.9399 -16.7734
-2.7770 -4.9107 -16.6909
-2.7770 -4.8687 -16.5732
-2.7770 -4.8534 -16.5307
-2.6882 -4.9399 -16.4805
-2.6806 -4.9399 -16.4221
-2.6882 -4.9107 -16.3989
-2.6806 -4.9107 -16.3408
-2.6882 -4.8687 -16.2825
-2.6882 -4.8534 -16.2404
Cris LaPierre
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
Mohammad Sami 2020년 3월 13일
편집: Mohammad Sami 2020년 3월 13일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

질문:

Yro
2020년 3월 13일

댓글:

2020년 3월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by