Convert variable-width text file numbers to UINT8 table?

2 views (last 30 days)
Hi :)
I have a file holding UINT8 integers:
  • Each line contains 1 to 8 integers
  • Each line is of width = 3 + (N-1)*4; where N is number of integers
  • Each value reserves exactly 3 characters (with leading space)
  • Each value is space-separated
  • Each line is '' terminated
Below is an example format:
//File begins
130 216 165 154 233 210 209 129
63 17 228
2 27 13 94 6 29 0 0
7 114 2 0 61 100 71
81 3 2 15 15 8 13 7
//File ends
I need to read out this data to a UINT8 table per below but cannot figure out a good way. I'd like to use a similar approach to this other solution where loops are avoided for good performance:
Goal = uint8([130 216 165 154 233 210 209 129 ; ...
63 17 228 0 0 0 0 0 ; ...
2 27 13 94 6 29 0 0 ; ...
7 114 2 0 61 100 71 0 ; ...
81 3 2 15 15 8 13 7 ]);

Answers (1)

C.J. Harris
C.J. Harris on 27 Jun 2014
It's not very elegant, and it's not very efficient - so enjoy:
nRaw = {'130 216 165 154 233 210 209 129'
' 63 17 228'
' 2 27 13 94 6 29 0 0'
' 7 114 2 0 61 100 71'
' 81 3 2 15 15 8 13 7'};
Goal = zeros(size(nRaw,1),8,'uint8');
for nRow = 1:size(nRaw)
Goal(nRow,:) = str2num(['uint8([',[nRaw{nRow}, char(repmat([32 32 32 48], ...
1, floor((31-length(nRaw{nRow}))/4)))],'])']);
end

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!