MATLAB Answers

0

How to find first non repeated (unique) character in a string?

Asked by Sam Accura on 14 Feb 2019 at 11:37
Latest activity Commented on by Sam Accura on 14 Feb 2019 at 14:10
I have already tried to find a Matlab function for this but doesnt seem to be one apart from 'unique' which only eliminates duplicates. Any ideas for code on how to do this?
For example, an input of 'hello' would return h or an input of 'radar' would return d.
The unique characters in 'hello' are h,e and o with h being the first in line
The unique character in 'radar' is only d and so this would also be the first
Any help would be appreciated

  2 Comments

please illustrate with an example
Example added to question - thank you

Sign in to comment.

2 Answers

Answer by madhan ravi
on 14 Feb 2019 at 12:37
 Accepted Answer

u=unique(s,'stable'); % where s is your input
Z=arrayfun(@(x)nnz(s==u(x)),1:numel(u));
Result=u(find(Z==1,1,'first'))

  1 Comment

Thank you very much - very helpful.

Sign in to comment.


Answer by Andrei Bobrov
on 14 Feb 2019 at 12:50

z = 'hello';
[a,~,c] = unique(z,'stable');
out = a(find(accumarray(c,1) == 1,1));

  0 Comments

Sign in to comment.