Math List Indexing

Let be Sa vector with unique elements, and let Sit be a subset of it, also with unique elements; for example, S={1,2,3,4,5,6}and s={1,3,4,6}. Now, given another vector c={7,8,9,7}, how can I create a vector C=[7,0,8,9,0,7], i.e. If S[[i]]is an element of b S, then it C[[i]]is equal to an element of b cwith the same index as S[[i]]in S, otherwise zero.

What I now look like

C=Array[0&,Length[S]];
j=1;
For[i=1,i<=Length[S],i++,If[MemberQ[s,S[[i]]],C[[i]]=c[[j]];j=j+1;]]; 

This works, but based on the MATLAB background, I hate loops for, and the above operation is a trivial indexing operation in matlab. I am sure there is a smarter way to achieve this la-mathematical style. Anyone have any suggestions?

+5
source share
5 answers

This is faster than published so far:

ss = {1, 2, 3, 4, 5, 6};   s = {1, 3, 4, 6};   c = {7, 8, 9, 7};

Replace[ss, Dispatch@Append[Thread[s -> c], _ -> 0], 1]
+4
source

You replace the elements of S with either the element c or 0, therefore:

ss = {1, 2, 3, 4, 5, 6}
s = {1, 3, 4, 6}
c = {7, 8, 9, 7}
r = Append[MapThread[Rule, {s, c}], Rule[_, 0]]
answer = Map[Replace[#, r] &, ss]
+5
source

. , , .

s = {1, 2, 3, 4, 5, 6};
subS = {1, 3, 4, 6};
c = {7, 8, 9, 7};
d= s /. {x_Integer :> If[MemberQ[subS, x], c[[Position[subS, x][[1, 1]]]], 0]}

, .

Mathematica , , .

+1
ss = {1, 2, 3, 4, 5, 6};
s = {1, 3, 4, 6};
c = {7, 8, 9, 7};
ss /. Join[MapThread[Rule, {s, c}],Thread[Rule[Complement[ss, s], 0]]]

EDIT :

answer = 0 ss; answer[[Position[ss, #, 1] & /@ s // Flatten]] = c;
+1

S {1, 2, ..., n} (, Range[n]), SparseArray 2 , @Mr. :

Normal[SparseArray[Thread[s -> c], n, 0]]
+1

All Articles