简体   繁体   中英

Matlab reading txt formatted file

If there is a .txt file in the format

Name, Home, 1, 2, 3, 3, 3, 3

It means the first two columns are string, and the rest are integers

How do I read first two column as vectors of strings, and another matrix as numeric values.

One way of doing this so you know exactly what's happening line by line is in the following piece of code:

fid = fopen('textfile.txt');
clear data

tline = fgetl(fid);
n = 1;
while ischar(tline)        
    data(n,:) = strsplit(tline(1:end),', ');
    n=n+1;
    tline = fgetl(fid);
end    

fclose(fid);

dataStrings = data(:,1:2);
dataValues = str2double(data(:,3:end));

where data contains everything in string type, dataStrings contains only first 2 columns as strings, and dataValues contains the rest of the columns as type double.

This way you get simple matrices, meaning you don't have to worry yourself with structures or cell arrays.

Use textscan :

fileID = fopen('sometextfile.txt');
C = textscan(fileID,'%s %s %f %f %f %f %f %f','Delimiter',','); % assuming you want double data types, change as required
fclose(fileID);
celldisp(C) % C is a cell array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM