필터 지우기
필터 지우기

How to read text file and put it in to a matrix format.

조회 수: 4 (최근 30일)
Jothi
Jothi 2012년 11월 9일
My input file input.txt has the following inputs.
input.txt=
a b c d f
a c
a c d f g
a b e h
a c e f
I want input file converted into a matrix format ie.,
input=
[a b c d f
a c 0 0 0
a c d f g
a b e h 0
a c e f 0];
how will do this.
thanks.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 9일
fid = fopen('file1.txt');
line1 = fgetl(fid);
res=line1;
while ischar(line1)
line1 = fgetl(fid);
res =char(res,line1)
end
fclose(fid);
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 9일
To add 0
[n,m]=size(res)
for k1=1:2:n
for k2=1:2:m
if isequal(res(k1,k2),' ')
res(k1,k2)='0'
end
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

David Barry
David Barry 2012년 11월 9일
You should try looking up the functions textread and textscan if you want to do this programatically. Alternatively you can use the data import wizard GUI.
  댓글 수: 1
David Barry
David Barry 2012년 11월 9일
uiimport will open the wizard or it can be found from the menus.

댓글을 달려면 로그인하십시오.


Andrei Bobrov
Andrei Bobrov 2012년 11월 9일
편집: Andrei Bobrov 2012년 11월 9일
f = fopen('test.txt'); c = textscan(f,'%s','Delimiter','\n');fclose(f);
c2 = c{1}(~cellfun(@isempty,c{1}))
c3 = regexp(c2,'\w*','match')
n = cellfun('size',c3,2);
m = max(n);
c4 = arrayfun(@(x,y)[c3{x},repmat({0},1,mod(-y,m))],(1:numel(n))',n(:),'un',0);
test = cat(1,c4{:});
or
fid = fopen('test.txt');
C = textscan(fid, '%s %s %s %s %s');
fclose(fid);
n = cellfun(@numel,C);
m = max(n);
C1 = cellfun(@(x,y)[x;repmat({'0'},mod(-y,m),1)],C,num2cell(n),'un',0)
Cout = [C1{:}]
Cout(cellfun(@isempty,Cout)) = {'0'}

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by