To read a word and indices

1 次查看(过去 30 天)
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