How to fill in initialized zero array with data?

7 ビュー (過去 30 日間)
Gary
Gary 2015 年 11 月 19 日
回答済み: Jaynik 2024 年 11 月 8 日 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.

回答 (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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by