Xingdong
Xingdong

Reputation: 1455

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.

Upvotes: 0

Views: 71

Answers (2)

acerne
acerne

Reputation: 33

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.

Upvotes: 1

am304
am304

Reputation: 13886

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

Upvotes: 0

Related Questions