- 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 (최근 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.
댓글 수: 0
답변 (1개)
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!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!