mathematica 中的列表索引
令 S
为具有唯一元素的向量,并且 s
是其子集,也具有唯一元素;例如,S={1,2,3,4,5,6}
和 s={1,3,4,6}
。现在给定另一个向量 c={7,8,9,7}
,如何创建向量 C=[7,0,8,9,0,7]
>,即,如果 S[[i]]
是 s
中的元素,则 C[[i]]
等于该元素在 c
中,其索引与 s
中的 S[[i]]
相同,否则为零。
我现在所拥有的看起来像
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;]];
这可行,但来自 MATLAB 背景,我讨厌 for
循环,并且上述操作是 matlab 中的一个简单的索引操作。我确信有一种更聪明的方法可以实现这一点,即数学风格。有人有建议吗?
Let S
be a vector with unique elements, and s
a subset of it, also with unique elements; e.g., 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 in s
, then C[[i]]
is equal to the element in c
with the same index as S[[i]]
in s
, else zero.
What I have right now looks 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 coming from a MATLAB background, I hate for
loops and the above operation is a trivial indexing operation in matlab. I'm sure there is a smarter way to accomplish this, a la mathematica style. Does anyone have suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您要将 S 的元素替换为 c 中的元素或 0,因此:
You are replacing elements of S with either an element in c or with 0, so:
这比迄今为止发布的速度要快:
This is faster than what has been posted so far:
编辑或:
EDIT or:
这是一种方法。可能还有很多其他的。
按照用户定义符号的惯例,我自始至终都使用小写变量名称。
Mathematica 使用花括号表示向量、列表、矩阵和表格。
Here's one way. There are probably many others.
I used lower case variable names throughout as is customary for user-defined symbols.
Mathematica uses curly braces are used for vectors, lists, matrices, and tables.
如果
S
始终采用{1, 2, ..., n}
形式(例如Range[n]
),则此使用SparseArray
的解决方案大约是 @ 的两倍先生。向导在我对非常大的列表的测试中的答案:If
S
is always of the form{1, 2, ..., n}
, (e.g.,Range[n]
) then this solution usingSparseArray
is about twice as fast as @Mr. Wizard's answer in my testing for very large lists: