is there an easy way to import data separated by brackets

조회 수: 6 (최근 30일)
Michael
Michael 2012년 10월 9일
I have some data in this form:
((0,0),(0.1,5),(0.2,7.5))
anyone have any idea how to import it? i would like it in a matrix in the form of
0 0
0.1 5
0.2 7.5
Thanks for your help
Mike
  댓글 수: 2
Michael
Michael 2012년 10월 9일
sorry i've just seen how useless this looks i want it in the form [0,0;0.1,5;0.2,7.5]
per isakson
per isakson 2012년 10월 9일
편집: per isakson 2012년 10월 9일
  • "import" implies text file?
  • the text file contains several rows?
  • does your comment imply that the result shall be a <3x2xnumber_of_lines > double array?

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

채택된 답변

per isakson
per isakson 2012년 10월 9일
편집: per isakson 2012년 10월 11일
Hint:
str = '((0,0),(0.1,5),(0.2,7.5))';
M = textscan( str, '%f%f%f%f%f%f' ...
, 'Delimiter', ',' ...
, 'Whitespace', '() ' ...
, 'CollectOutput', true );
>> M{:}
ans =
0 0 0.1000 5.0000 0.2000 7.5000
>>
and reshape
>> transpose(reshape( M{:}, [2,3]))
ans =
0 0
0.1000 5.0000
0.2000 7.5000
.
replace str by a file id
fid = fopen( ...
M = textscan( fid, ...
.
--- reading from file ---
fid = fopen( 'cssm.txt' );
M = textscan( fid, '%f' ...
, 'Delimiter' , ',' ...
, 'Whitespace' , '() ' ...
, 'CollectOutput', true );
fclose( fid );
permute( reshape( M{:}, 2,3,4 ), [ 2,1,3 ] )
permute( reshape( M{:}, 2,3,[]), [ 2,1,3 ] )
where cssm.txt contains
((0,0),(0.1,5),(0.2,7.5))
((1,1),(0.1,5),(0.2,7.5))
((2,2),(0.1,5),(0.2,7.5))
((3,3),(0.1,5),(0.2,7.5))
outputs
ans(:,:,1) =
0 0
0.1000 5.0000
0.2000 7.5000
ans(:,:,2) =
1.0000 1.0000
0.1000 5.0000
0.2000 7.5000
ans(:,:,3) =
2.0000 2.0000
0.1000 5.0000
0.2000 7.5000
ans(:,:,4) =
3.0000 3.0000
0.1000 5.0000
0.2000 7.5000
.
--- a variation ---
fid = fopen( 'cssm.txt' );
M = textscan( fid, '%f' ...
, 'Delimiter' , ',() ' ...
, 'MultipleDelimsAsOne' , true ...
... , 'Whitespace' , '() ' ...
, 'CollectOutput' , true );
fclose( fid );
permute( reshape( M{:}, 2,3,[] ), [ 2,1,3 ] )
.
Comment: These constructs does not use the information hold by the parentheses. Furthermore, there is not test that the file confirms to the assumed format. With some clever use of regular expressions it would be possible to make a more robust code.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by