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

1 回表示 (過去 30 日間)
alicin
alicin 2013 年 1 月 22 日
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 Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by