- sprintf: https://www.mathworks.com/help/matlab/ref/string.sprintf.html
- size: https://www.mathworks.com/help/matlab/ref/double.size.html
How to fill in initialized zero array with data?
7 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
Jaynik
on 8 Nov 2024 at 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!
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!