To read a word and indices

1 vue (au cours des 30 derniers jours)
Nicle Davidson
Nicle Davidson le 24 Sep 2021
Commenté : Stephen23 le 24 Sep 2021
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.

Réponse acceptée

DGM
DGM le 24 Sep 2021
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);

Plus de réponses (0)

Catégories

En savoir plus sur Language Support dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by