How to realize this vector operation ?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Azzi Abdelmalek
2013-5-3
编辑:Azzi Abdelmalek
2013-5-3
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 个评论
更多回答(1 个)
Azzi Abdelmalek
2013-5-3
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 个评论
Azzi Abdelmalek
2013-5-3
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.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!