How can read specific text from file then convert it to numeric value

6 次查看(过去 30 天)
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

回答(2 个)

Image Analyst
Image Analyst 2013-1-23
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

Jan
Jan 2013-1-24
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) = [];

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by