How to realize this vector operation ?

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 .....];

 采纳的回答

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 个评论

Thank you sir for the solution, but can I do the same with no loops. :)
I do not see how to do it
sir there was an error......
d4=cos(2*pi*293.665*(0:1/44100:.25));
f4=cos(2*pi*349.228*(0:1/44100:.25));
e4=cos(2*pi*329.628*(0:1/44100:.25));
g4=cos(2*pi*391.995*(0:1/44100:.25));
c5=cos(2*pi*523.251*(0:1/44100:.25));
bb4=cos(2*pi*466.164*(0:1/44100:.25));
a4=cos(2*pi*440*(0:1/44100:.25));
c4=cos(2*pi*261.626*(0:1/44100:.25));
x=[c4 c4 d4 c4 f4 e4 c4 c4 d4 c4 g4 f4 c4 c4 c5 a4 f4 e4 d4 bb4 bb4 a4 f4 g4 f4];
v={a4,bb4,c4,c5,d4,e4,f4,g4};
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)
out =
Columns 1 through 15
8 8 8 8 8 8 1 8 8 8 8 8 8 6 7
Columns 16 through 30
8 8 8 8 8 8 6 8 8 8 8 1 8 8 8
Columns 31 through 41
8 8 8 8 6 8 8 8 8 6 7
But actually the answer must be out=[3 3 5 3 7 6 3 3 5 3 8 7 3 3 4 1 7 6 5 2 2 1 7 8 7] right

请先登录,再进行评论。

更多回答(1 个)

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 个评论

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.
thankyou sir for the efforts..... :)

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 MATLAB Support Package for Arduino Hardware 的更多信息

产品

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by