Importing txt files and using loops
    9 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Pouyan Msgn
 el 11 de Mzo. de 2020
  
    
    
    
    
    Respondida: BobH
      
 el 11 de Mzo. de 2020
            I have three txt files and I want to use their nummerical data in Matlab
How can I ignore and neglect non-numeric texts? I want Matlab to import just numbers, there two columns of numbers in each file and I want just those numbers
I have more than one file. Here I have three files. Is it possible to use for loop to import these files and buy time?
0 comentarios
Respuesta aceptada
  Mario Malic
      
 el 11 de Mzo. de 2020
        
      Editada: Mario Malic
      
 el 11 de Mzo. de 2020
  
      %% Reading the file
FID_F_1 = fopen(filename , 'r'); 
i = 1;
tline = fgetl(FID_F_1);
A{i} = tline;
while ischar(tline)
    i = i+1;
    tline = fgetl(FID_F_1);
    A{i} = tline;
end
fclose(FID_F_1);
Now all text is saved in variable A.
for ii = line where data starts : line where data ends
X_Temp = str2num(A{ii}); %converts the string line into array
X = X_Temp(1,1); %
Y = X_Temp(1,2); % Getting the values
end
0 comentarios
Más respuestas (2)
  Subhamoy Saha
      
 el 11 de Mzo. de 2020
        
      Editada: Subhamoy Saha
      
 el 11 de Mzo. de 2020
  
      Here I have tested with your J94.txt file
filename = 'C:\Users\Desktop\J94.txt'; %% change filepath accordingly
delimiter = ' ';
startRow = 33;
formatSpec = '%f%f%*s%*s%[^\n\r]';
fileID = fopen(filename,'r');
textscan(fileID, '%[^\n\r]', startRow-1, 'WhiteSpace', '', 'ReturnOnError', false, 'EndOfLine', '\r\n');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false);
fclose(fileID);
Col1 = dataArray{:, 1};
Col2 = dataArray{:, 2};
clearvars filename delimiter startRow formatSpec fileID dataArray ans;
You can use multiple files using loop if those file names are in some order. Otherwise use uigetfile().
0 comentarios
  BobH
      
 el 11 de Mzo. de 2020
        Similar to Mario Malic but using regular expressions
R = [];  % init to empty
    fid = fopen('J94.txt','r');
    t = fgetl(fid);
    while( ischar(t) )
        reNum = '([0-9.E\+]+)';
        m = regexp(t, ['^\s*' reNum '\s+' reNum], 'tokens','once');
        if( length(m) == 2 )  % found two matches in the line
            R(end+1,:) = cellfun(@str2num, m);
        end
        t = fgetl(fid);
    end
    fclose('all');
0 comentarios
Ver también
Categorías
				Más información sobre Large Files and Big Data en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



