필터 지우기
필터 지우기

Save each vector result from a for loop into a matrix

조회 수: 3 (최근 30일)
Arthur Batte
Arthur Batte 2020년 7월 6일
답변: Balavignesh 2024년 6월 27일
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
  댓글 수: 1
Nihal
Nihal 2024년 6월 14일
Please attach the files, Cannot see any attachment.

댓글을 달려면 로그인하십시오.

답변 (1개)

Balavignesh
Balavignesh 2024년 6월 27일
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

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by