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 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