Convert a fixed width char array into a column vector
8 ビュー (過去 30 日間)
古いコメントを表示
Hello! I have troubles converting numbers from a char array to double format. The char array always has the dimensions 1x48. Every 8 characters represent an integer. Sometimes there are spaces between numbers and sscanf fails to give the results I need. For example:
aa = ' 1703434 42 1012275140184521401845314018473';
sscanf(aa,'%8d')
ans =
1703434
42
10122751
40184521
40184531
4018473
should return in fact
ans =
1703434
42
10122751
14018452
14018453
14018473
The reason why I don't use str2double for each 8 characters in 'aa' is that it gets very slow for many conversions. The original file I read also contains other words, and this array 'aa' is only a part of each line I read. So far sscanf was the fastest method and it worked well until this line was encountered.
Could anyone please explain me why sscanf behaves like this? Is there any quick alternative?
0 件のコメント
採用された回答
その他の回答 (2 件)
Stephen23
2020 年 7 月 28 日
編集済み: Stephen23
2020 年 7 月 28 日
This will be quite efficient:
>> aa = ' 1703434 42 1012275140184521401845314018473';
>> vec = sscanf(sprintf('%c%c%c%c%c%c%c%c,',aa),'%f%*[ ,]')
vec =
1703434
42
1012275
14018452
14018453
14018473
2 件のコメント
Stephen23
2020 年 7 月 28 日
Timing for 1e4 iterations:
Elapsed time is 2.80135 seconds. % reshape, repmat, sscanf
Elapsed time is 7.16556 seconds. % reshape, str2num
Elapsed time is 0.92013 seconds. % this answer
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!