Is it possible to section a very long string into a matrix?

4 次查看(过去 30 天)
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?

回答(2 个)

Matt J
Matt J 2013-4-19
编辑:Matt J 2013-4-19
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 个评论
Matt J
Matt J 2013-4-19
编辑:Matt J 2013-4-19
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
Cedric 2013-4-19
编辑:Cedric 2013-4-19
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 个评论
Cedric
Cedric 2013-4-19
编辑:Cedric 2013-4-19
Yes, I was too, but parsing format spec is probably time consuming even when the string is short/simple (if only to detect that it is simple). The input parser probably also adds a non-negligible overhead.
Jan
Jan 2013-4-19
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'.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by