Read text file line by line to columns
    조회 수: 7 (최근 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 Type Identification에 대해 자세히 알아보기
			
	제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


