How can read specific text from file then convert it to numeric value
5 views (last 30 days)
Show older comments
Hi I am trying to read text from file.
Text file format is like;
a b b a c d and continue
then I have to convert this character to predetermined number.
ex. when I read 'a' from text, first number of array is 100, if b read second number of array 200 and c=300 and d=400.
How can I do this.
I start with this;
data=fopen('data.txt','r')
d=fscanf(data,'%s');
I read strings but there is no whitespace.
then what kind of "if or which" statement I have to write?
Thanks for all
0 Comments
Answers (2)
Image Analyst
on 23 Jan 2013
Try this:
% Read a line using fgetl() and get something like this:
s = 'a b b a c d'
% Get rid of spaces
s(s==' ') = []
% Convert into numbers: 1 for a, 2 for b, etc.
sIndex = lower(s) - 'a' + 1
% Go through them all, running the appropriate code for that number.
for k = 1:length(sIndex)
fprintf('For k = %d, Character = %s, index = %d\n', k, s(k), sIndex(k));
switch sIndex(k)
case 1
fprintf(' Run algorithm #1\n');
case 2
fprintf(' Run algorithm #2\n');
case 3
fprintf(' Run algorithm #3\n');
case 4
fprintf(' Run algorithm #4\n');
otherwise
fprintf(' Unknown case %d\n', sIndex(k));
end
end
0 Comments
Jan
on 24 Jan 2013
Here the characters 'a' etc are used as indices - this works because they are converted to their ASCII codes implicitly:
table = zeros(1,256);
table('abcdefg') = [100, 200, 300, 400, 500, 600, 700];
fid = fopen(FileName, 'r');
data = fread(fid);
data(data == 0) = 1;
result = table(data);
% Remove remaining zeros on demand:
result(result == 0) = [];
0 Comments
See Also
Categories
Find more on Data Type Conversion 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!