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

6 visualizaciones (últimos 30 días)
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

Respuestas (2)

Image Analyst
Image Analyst el 23 de En. de 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

Jan
Jan el 24 de En. de 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) = [];

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by