Is it possible to section a very long string into a matrix?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I am trying to break up a very long character string into sections that I can put into a matrix.
example: '56748946489148461898434919946189189454961894564349894389' and I want to extract the numbers in groups of say 4 [(5674),(8946), etc], and put them into a (25,1) matrix, each group of 4 being the content for the row. Is there a way to use a reshape or a loop, or any other ideas about how I would do this?
0 comentarios
Respuestas (2)
Matt J
el 19 de Abr. de 2013
Editada: Matt J
el 19 de Abr. de 2013
You can do as follows, although I don't know what you mean by a 25x1 matrix. If each row is to contain 4 digits, then it would have to be 14x4
>> A='56748946489148461898434919946189189454961894564349894389';
>> B=reshape(A,4,[]).',
B =
5674
8946
4891
4846
1898
4349
1994
6189
1894
5496
1894
5643
4989
4389
>> whos B
Name Size Bytes Class Attributes
B 14x4 112 char
1 comentario
Matt J
el 19 de Abr. de 2013
Editada: Matt J
el 19 de Abr. de 2013
Or if you mean that you want to convert the strings to actual numbers, you can do something like this
>> B=(reshape(A,4,[]).' - '0')*10.^(3:-1:0).'
B =
5674
8946
4891
4846
1898
4349
1994
6189
1894
5496
1894
5643
4989
4389
>> whos B
Name Size Bytes Class Attributes
B 14x1 112 double
Cedric
el 19 de Abr. de 2013
Editada: Cedric
el 19 de Abr. de 2013
One way would be:
>> s = '56748946489148461898434919946189189454961894564349894389' ;
>> num = sscanf(s, '%4f')
num =
5674
8946
4891
4846
1898
4349
1994
6189
1894
5496
1894
5643
4989
4389
EDIT 1: Matt answered while I had the answer opened and had to take a break for managing a hungry cat ;-) .. so, note that his answer is more efficient than SSCANF. I leave my answer for the record though.
EDIT 2: you can check this out:
to get an idea about how "more efficient" Matt's answer is actually.
3 comentarios
Jan
el 19 de Abr. de 2013
Strange. SSCANF is surprisingly fast for some tasks, e.g. for converting a cell string to a numerical vektor. See e.g. FEX: Fast str2double, which should be much faster actually than this naive M-version:
d = reshape(sscanf(sprintf('%s#', c{:}), '%g#'), size(c));
Inspite of the time-consuming creation of the large temporary string, this beats a C-implementation, which scans each string separately by sscanf(), strtod() of the C-libs. Therefore I conclude that sscanf must be extremely efficient for this case. Perhaps use '%4d' instead of '%4f'.
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!