is there an easy way to import data separated by brackets

7 views (last 30 days)
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 Comments
Michael
Michael on 9 Oct 2012
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 on 9 Oct 2012
Edited: per isakson on 9 Oct 2012
  • "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?

Sign in to comment.

Accepted Answer

per isakson
per isakson on 9 Oct 2012
Edited: per isakson on 11 Oct 2012
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.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!