Read text file line by line to columns
18 次查看(过去 30 天)
显示 更早的评论
Hello community,
I have the data in this form
.557 .331 .069 .065 .101 .052 .109 .045 .114 .041 .117 .041 .109 .451 .234 -.058 .347 .406 -.005 .948 .252 -.007 .140 .024 .124 .036 .113 .045 .105 .052 .097 .059 .090 .064 .085 .068 .080 .071 .077 .073 0.075
and I want the data to be read as this form
0.557
0.331
0.069
0.065
0.101
0.052
etc
Please help
2 个评论
回答(2 个)
Dyuman Joshi
2024-5-7
编辑:Dyuman Joshi
2024-5-7
in = readmatrix('RANCHOD - Copy.txt');
out = reshape(in.', [], 1);
disp(out)
0 个评论
Pavan Sahith
2024-5-7
编辑:Pavan Sahith
2024-5-7
Hello Shimna,
I see that you are trying to read the data from a text file and convert it into a column format in MATLAB, you can follow these steps.
- Read the File: Use 'fopen' to open the file for reading.
- Read Lines and Split: Use 'fgetl' or 'fgets' in a loop to read the file line by line. Then, split the line into individual numbers.
- Convert to Numbers: The split parts will be strings, so convert them into numbers using 'str2double'.
- Store in an Array: Initialize an array before the loop and append each number to this array.
- Close the File: After reading all lines, close the file using 'fclose'.
This example assumes that your data is stored in a text file called data.txt.
% Open the file for reading
fid = fopen('data.txt', 'rt');
% Check if the file was opened successfully
if fid == -1
error('File cannot be opened');
end
% Initialize an empty array to store the numbers
data = [];
% Read the file line by line
while ~feof(fid)
line = fgetl(fid); % Read one line from the file
% Split the line into strings based on spaces
numbersStr = strsplit(line);
% Convert strings to numbers and remove any NaN values that might occur from spaces
numbers = str2double(numbersStr);
numbers = numbers(~isnan(numbers));
% Append the numbers to the data array
data = [data; numbers']; % Transpose to make it a column
end
% Close the file
fclose(fid);
% Display the data
disp(data);
You can refer to the following MathWorks Documentation to know more about some important functions used.
I hope this will guide you for reading and structuring data in MATLAB exactly as you envisioned
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!