How to fill in initialized zero array with data?

7 visualizaciones (últimos 30 días)
Gary
Gary el 19 de Nov. de 2015
Respondida: Jaynik el 8 de Nov. de 2024 a las 6:13
Supposed I have a 10 data files with up to 1000 lines each. But some files might only have 885 lines, some might have 997 lines. I have pre-allocated an array "a":
a = zeros(1000,10)
How can I dlmread each file, filling in the rows of array "a", until the file reaches the EoF? Then the rest of the unfilled rows of "a" still remain as 0? Thank you very much, it has puzzled me greatly.

Respuestas (1)

Jaynik
Jaynik el 8 de Nov. de 2024 a las 6:13
Hi Gary,
You can use the size function to get the number of lines in the current file after reading using dlmread. Using the number of lines, you can fill the corresponsing column. Though the rest of all the unfilled rows of a will remain 0.
Here is a sample code for the same:
a = zeros(1000, 10);
for i = 1:10
% Construct the filename (assuming files are named 'file1.txt', 'file2.txt', etc.)
filename = sprintf('file%d.txt', i);
data = dlmread(filename);
numLines = size(data, 1);
a(1:numLines, i) = data;
end
Note that dlmread is not recommended, you can use readmatrix directly by replacing dlmread in the above code.
Please refer to the following documentation to read more about these functions:
Hope this helps!

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by