Gohann
Gohann

Reputation: 155

read a txt file to matrix and cellarray Matlab

I have a txt file with those entries and I would like to know how to get the numerical values from the second column until the last column in a matrix and the first column in a cell array.

I've tried with import data and fscanf and I dont understand what's going on.

CP6  7,2    -2,7     6,6 

P5  -5,8    -5,9     5,8

P6   5,8    -5,9     5,8

AF7 -5,0     7,2     3,6

AF8  5,0     7,2     3,6

FT7 -7,6     2,8     3,6

Upvotes: 0

Views: 143

Answers (3)

EngrStudent
EngrStudent

Reputation: 2022

Have you tried xlsread? It makes a numeric array and two non-numeric arrays.

[N,T,R]=xlsread('yourfilename.txt')

but your data is not comma delimited. It also looks like you are using a comma to represent a decimal point. Does this array have 7 columns or 4? Because I'm in the US, I'm going to assume you have paired coordinates and the comma is one kind of delimiter while the space is a second one.

So here is something klugy, but it works. It is a gross ugly hack, but it works.

%housekeeping
clc

%get name of raw file
d=dir('*22202740*.txt')

%translate from comma-as-decimal to period-as-decimal
fid = fopen(d(1).name,'r')  %source
fid2= fopen('myout.txt','w+')  %sink

while 1
    tline = fgetl(fid);  %read
    if ~ischar(tline), break, end  %end loop
    fprintf(fid2,'%s\r\n',strrep(tline,',','.')) %write updated line to output
end

fclose(fid)
fclose(fid2)

%open, gulp, parse/store, close
fid3 = fopen('myout.txt','r');
C=textscan(fid3,'%s %f %f %f ');
fclose(fid3);

%measure waist size and height
[n,m]=size(C);
n=length(C{1});

%put in slightly more friendly form
temp=zeros(n,m);

for i=2:m
    t0=C{i};
    temp(:,i)=t0;
end

%write to excel
xlswrite('myout_22202740.xlsx',temp(:,2:end),['b1:' char(96+m) num2str(n)]);
xlswrite('myout_22202740.xlsx',C{1},['a1:a' num2str(n)])

%read from excel
[N,T,R]=xlsread('myout_22202740.xlsx')

If you want those commas to be decimal points, then that is a different question.

Upvotes: 0

The-Duck
The-Duck

Reputation: 509

This should give you what you want based on the text sample you supplied.

fileID = fopen('x.txt'); %open file x.txt
m=textscan(fileID,'%s %d ,%d %d ,%d %d ,%d');
fclose(fileID); %close file
col1 = m{1,1}; %get first column into cell array col1 
colRest = cell2mat(m(1,2:6)); %convert rest of columns into matrix colRest

Lookup textscan for more info on reading specially formatted data

Upvotes: 1

Etienne
Etienne

Reputation: 1012

This function should do the trick. It reads your file and scans it according to your pattern. Then, put the first column in a cell array and the others in a matrix.

function [ C1,A ] = scan_your_txt_file( filename )
  fid = fopen(filename,'rt');

  C = textscan(fid, '%s %d,%d %d,%d %d,%d');
  fclose(fid);

  C1 = C{1};
  A = cell2mat(C(2:size(C,2)));
end

Upvotes: 0

Related Questions