Having trouble with this problem
Show older comments
Here is the question:
The file upcs.txt contains a list of UPC codes that were scanned in a grocery store. Each line should, ideally, contain 12 digits corresponding to a single product. Read the contents of the file and store the entries into an m x 12 sized numeric array named codes, where m is the number of valid lines in the le. Lines that have less or more than 12 digits should be discarded. Some lines with 12 digits may have digits that were not correctly scanned, which were replaced by the letter X'. These missing digits should be represented in the array codes by the integer-1'. After processing the le, print the total number of lines read, the number of lines discarded, and the number of lines correctly processed and stored in codes.
upcs.txt:
X9096X082489
921642004330
810905023006
733554287763
413527622XX1
287X35871528
100093334850
764491079X90
1537X8886614
086755751640
860053705316
980098819206
038356338621
577577248178
82825685985
684580785580
736657539753
71113617151
935014271064
702345843488
58316491755
110118383664
333841856254
996003013296
495258095746
4457870230
684104168936
522784039910
6504512835
699553963094
853110488363
554147120089
Here is my code so far:
fid = fopen('upcs.txt');
mat = [];
if fid == -1
disp('File open was not successful')
else codes = {};
while feof(fid) == 0
aline = fgetl(fid);
num = strtok(aline);
codes = [codes; num]
end;
[m n] = size(codes)
discard = 0
for i = 1:m
len = length (codes(i))
if len ~= 12
codes = [];
discard = discard + 1
else
char(codes(i))
codes = strrep(codes, 'X', '-1')
end
end
codes
end
The trouble I am having is that I don't know how to delete the codes that have less or more than 12 digits in my code.
Answers (1)
Image Analyst
on 14 Mar 2013
Edited: Image Analyst
on 15 Mar 2013
I think your approach is all wrong. Don't add them all and then try to delete the bad ones. Just read a line and check it immediately. Only add it to your final array if it's good.
fid = fopen('upcs.txt');
if fid == -1
disp('File open was not successful')
else
codes = [];
while feof(fid) == 0
% Read one single line of text.
singleLineOfText = fgetl(fid);
% See if it has an X in it.
xLocation = strfind(singleLineOfText, 'X');
% Append it if it is exactly 12 characters long with no X in it.
if length(singleLineOfText) == 12 && isempty(xLocation)
codes = [codes; singleLineOfText];
else
fprintf('Discarding %s\n', singleLineOfText);
end
end
% print out final codes to command window:
fprintf('\nFinal codes = \n');
codes
end
Categories
Find more on Scripts 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!