Read text file line by line to columns
18 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Dyuman Joshi
am 7 Mai 2024
Bearbeitet: Dyuman Joshi
am 7 Mai 2024
in = readmatrix('RANCHOD - Copy.txt');
out = reshape(in.', [], 1);
disp(out)
0 Kommentare
Pavan Sahith
am 7 Mai 2024
Bearbeitet: Pavan Sahith
am 7 Mai 2024
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 Kommentare
Siehe auch
Kategorien
Mehr zu Data Import and Export finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!