is there an easy way to import data separated by brackets
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
per isakson
il 9 Ott 2012
Modificato: per isakson
il 9 Ott 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?
Risposta accettata
per isakson
il 9 Ott 2012
Modificato: per isakson
il 11 Ott 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Import and Export in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!