To read a word and indices

조회 수: 1 (최근 30일)
Nicle Davidson
Nicle Davidson 2021년 9월 24일
댓글: Stephen23 2021년 9월 24일
If I read a word directly such as:
word = 'CABDABCCDAA';
[uniqueLetters,~,ind] = unique(word);
disp(ind')
The ind would be such as:
3 1 2 4 1 2 3 3 4 1 1
But I need to read from a file, which could be a long file, but as an example I get the first 3 line of it:
12 CABDABCCDAA
10 jonathan
87658 david
so I did this:
inlist = fopen('test.txt');
linx = fgetl(inlist);
while ischar(linx)
x = strsplit(linx);
word=x(1,2);%This would get the word for me, which we put statically in the first example above
disp(toWord);
[uniqueLetters,~,ind] = unique(word);
disp(uniqueLetters);%the output is the same as the output of toWord
disp(ind);
end
fclose(inlist);
Here however I dont get
3 1 2 4 1 2 3 3 4 1 1
but only this output:
1
How can I get the same output, I think my mistake is to get a cell from the matrix where I do toWord=x(1,2); but I am not sure how to fix this.

채택된 답변

DGM
DGM 2021년 9월 24일
Something like this should be a start.
fid = fopen('test.txt');
while true
linx = fgetl(fid);
if ~ischar(linx); break; end
x = strsplit(linx);
word=x{1,2}; % This would get the word for me, which we put statically in the first example above
[uniqueLetters,~,ind] = unique(word);
disp(word); % toWord is undefined
disp(uniqueLetters); % the output is the same as the output of toWord
disp(ind.');
end
CABDABCCDAA
ABCD
3 1 2 4 1 2 3 3 4 1 1
jonathan
ahjnot
3 5 4 1 6 2 1 4
david
adiv
2 1 4 3 2
fclose(fid);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by