in a column, value 2 replace with 1 and value 1 & 3 replace with 2. The code i wrote below got problem:
S=[1 1 1 2 2 3 3 3 3];
S(S==2)=1; S(S==1)=2; S(S==3)=2;
result:
S=[2 2 2 2 2开发者_开发知识库 2 2 2 2]
However, the result i wan to get is S=[2 2 2 1 1 2 2 2 2]. does anyone can help?
That is happening because when in the S(S==1)=2;
step, you are affected by the modifications from the S(S==2)=1;
step. Try this
S = [1 1 1 2 2 3 3 3 3];
S_copy = S;
S(S_copy == 2) = 1; S(S_copy == 1) = 2; S(S_copy == 3) = 2;
or you could also save the results of the tests into separate variables:
S = [1 1 1 2 2 3 3 3 3];
f1 = (S == 2);
f2 = (S == 1);
f3 = (S == 3);
S(f1) = 1; S(f2) = 2; S(f3) = 2;
Instead of manually replacing each value, you can use an extra matrix to define a "map" from input values in S to output values.
>> S = [1 1 1 2 2 3 3 3 3]; % input
>> M = [2 1 2]; % M[i] = j -> map value i to j
>> S = M(S) % compute output
S =
2 2 2 1 1 2 2 2 2
This operation should be really fast in Matlab.
Note that this methods works as long as the values in S can be interpreted as index values (that is, they are integers and not too large).
your are getting closer but the problem arises once you change all the 2's to one.
after this statement
S(S==2)=1;
the array looks like this
S=[1 1 1 1 1 3 3 3 3];
and after the other two statements S(S==1)=2; S(S==3)=2;
your array will obviously have all 2's.
Instead of
S(S==2)=1; S(S==1)=2; S(S==3)=2;
you can do like this:
S(S==2)=-1; S(S==1)=2; S(S==3)=2;S(S==-1)=1;
i.e. in the first step change all the 2
's to some other value(e.g. -1
here) and then do the required conversion i.e. S(S==-1)=1
;
精彩评论