Easiest way to read a txt file(with char and numbers) into a numerical array/matrix?

6 views (last 30 days)
Hi all, really frustrated with this one problem. Basically there is a txt file that has lines of code, code being a mixture of letters and numbers (of different length) WITHOUT commas and spaces in between them ie: one code from the txt file is X32W21039A23
I need to read it into an numerical array/matrix so that it will be easy for me to manipulate it, AND I have to replace the letters with their corresponding numbers from a table. This is what I currently have
fid = fopen('upcs.txt');
mat = [];
if fid == -1
disp('File open was not successful')
else
while feof(fid) == 0
% Read contents of file and store into a matrix
aline = fgetl(fid);
[P] = sscanf(aline, '%s');
if length(A) == 12
mat = [mat P];
end
end
codes =reshape(mat, length(mat)/12, 12)
Basically I have removed all the lines from the txt file that were not 12 figures long (I can do that), and transferred the remaining lines into a character array, 'mat'. However, mat is a character array, not a numerical one. I've tried such functions as cell2mat and str2num, but to no avail, for I believe the codes are treated as cells or strings, rather than numbers. I believe I need to put spaces between the strings in the array.
So to sum up, can anyone help me easily transfer the codes in the txt file into a manner such that I can easily manipulate it like a vector of numbers ie: [1 2 3] thanks
  1 Comment
Walter Roberson
Walter Roberson on 13 Mar 2013
Edited: Walter Roberson on 13 Mar 2013
How should your X32W21039A23 be broken up? 'X' 32 'W' 1039 'A' 23 ? You indicate the numbers are of varying length and that the total length is 12: do the numbers each go until the next letter? Does the line always start with a letter? Are there always 3 pairs of letter then number ?

Sign in to comment.

Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!