How to fill in initialized zero array with data?

7 次查看(过去 30 天)
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.

回答(1 个)

Jaynik
Jaynik 2024-11-8,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!

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by