# To read a word and indices

24 views (last 30 days)
Nicle Davidson on 24 Sep 2021 at 4:55
Commented: Stephen on 24 Sep 2021 at 7:51
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 on 24 Sep 2021 at 5:29
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
2 1 4 3 2
fclose(fid);
Stephen on 24 Sep 2021 at 7:51
while ~feof(fid)