필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Ryan Dillingham
Ryan Dillingham 2013년 4월 18일
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