Save each vector result from a for loop into a matrix

2 views (last 30 days)
hello i kindly request for assistance. i would like to read 3 files from a file named filenr.lis. this file contains the names of these files that are stored in a directory called wavf. using a for loop, i would like the result of each file read in a matrix, one column per result. These files are not of the same length. See attached files.
Thank you

Answers (1)

Balavignesh
Balavignesh on 27 Jun 2024
Hi Arthur,
As per my understanding, you have text file containing the names of all the files you want to read and store the result in a matrix.There are different functions to read different formats. I am assuming the files in 'wavf' directory are in a format that 'load' function can read (e.g. MAT files).
You could use 'textscan' function to read the filenames from 'filenr.lis'. Then, you can loop through each file name, construc the full path and read the file's contents using 'load' function. Initialize the result matrix with 'NaN' values to handle different lengths. Populate the result matrix with the data from each file, ensuring each file's data is in a separate column.
The following code snippet may help you understand this:
% Read the list of file names from filenr.lis
fileList = 'filenr.lis';
dirPath = 'wavf';
% Open the file containing the list of file names
fid = fopen(fileList, 'r');
if fid == -1
error('Cannot open file: %s', fileList);
end
% Read all file names into a cell array
fileNames = textscan(fid, '%s');
fileNames = fileNames{1};
fclose(fid);
% Initialize a cell array to hold the data from each file
data = cell(length(fileNames), 1);
% Loop through each file and read its contents
for i = 1:length(fileNames)
% Construct the full path to the file
filePath = fullfile(dirPath, fileNames{i});
% Read the data from the file
fileData = load(filePath);
% Store the data in the cell array
data{i} = fileData;
end
% Find the maximum length of the data vectors
maxLength = max(cellfun(@length, data));
% Initialize the result matrix with NaNs to handle different lengths
resultMatrix = NaN(maxLength, length(fileNames));
% Populate the result matrix with the data from each file
for i = 1:length(fileNames)
resultMatrix(1:length(data{i}), i) = data{i};
end
% Display the result matrix
disp(resultMatrix);
Feel free to adjust the script based on your specific requirements and the format of your files.
Have a look at the following documentation links to have more information on:
Hope that helps!
Balavignesh

Categories

Find more on Text Data Preparation in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!