How to realize this vector operation ?
2 views (last 30 days)
Show older comments
I have a vector X and 5 states (each state is a vector like A B C D E as below).
A = [10 11 12];
B = [20 25];
C = [37 37];
D = [49];
E = [57 51 54];
X = [ 10 11 12 20 25 37 37 49 57 51 54 ....];
[10 11 12] corresponds to A and will be represented as 1 in the resultant vector Z, like that 2 for B 3 for C etc.
How can I obtain Z from X. Here Z will be as below : Z = [1 2 3 4 5 .....];
0 Comments
Accepted Answer
Azzi Abdelmalek
on 3 May 2013
Edited: Azzi Abdelmalek
on 3 May 2013
A = [10 11 12];
B = [20 25];
C = [37 37];
D = [49];
E = [57 51 54];
X = [ A C B E D E E A D];
v={A,B,C,D,E};
y=zeros(1,numel(X));
for k=1:numel(v)
id=find(diff([0 ismember(X,v{k})])==1);
y(id)=k;
end
out=y(y~=0)
3 Comments
More Answers (1)
Azzi Abdelmalek
on 3 May 2013
A = [10 11 12];
B = [20 25];
C = [37 37];
D = [49];
E = [57 51 54];
v={A,B,C,D,E}
X = [ A C B E D E E A D]
a=cellfun(@(x) find(diff([0 ismember(X,x)])==1),v,'un',0);
b=arrayfun(@(x) x*ones(1,numel(a{x})),1:numel(v),'un',0);
c=cell2mat([a;b])';
d=sortrows(c,1)
out=d(:,2)'
2 Comments
Azzi Abdelmalek
on 3 May 2013
The for loop is much faster then answer 2:
running those answers 1000 times:
Answer 1: Elapsed time is 0.055467 seconds.
Answer 2: Elapsed time is 0.899734 seconds.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!