2011-03-14 83 views
4

這個問題在某種程度上延續了我在此處詢問的問題:Simple way to delete a matrix column in Mathematica @belisarius和@Daniel提供了非常有用的答案。在Mathematica中選擇/刪除矩陣中行/列的清單的有效方法

我一般要做的是從矩陣中提取特定的行和列,或者在指定的元素被刪除後保留下來。因此,這可以正式寫成:找到TakeOperator和Drop Operator如下:

TakeOperator [A,{i1,..,ip},{j1,...,jq}] =(A [[ik] ] [[JL]])(1 < = K < = p,1 < = 1 < = q)= Table[A[[ik]][[jl]],{k,p},{l,q}]

我們注意到IC = {I'1,...,I'p'} = Complement {{1,...,Length[A]},{i1,...,ip}]; Jc = {j'1,...,j'q'} = Complement [{1,...,Length[A]} {J1,...,JQ}]; DropOperator [A,{i1,..,ip},{j1,...,jq}] =(A [[ik]] [[jl]])(= k'< = p ',< = 1'< = q')= Table[A[[ik']][[jl']],{k',p'},{l','q}]

儘管如上所述的Table這樣做,但以這種方式使用表是非常低效的。

只給一個想法,我把@貝利薩留例如:

In: [email protected][a = RandomInteger[1000, {5000, 5000}];] 

Out:0.218 

In:Clear[b,c] 

In:[email protected][ 
    b = Table[ 
    If[i < 100, If[j < 100, a[[i]][[j]], a[[i]][[j + 1]]], 
    If[j < 100, a[[i + 1]][[j]], a[[i + 1]][[j + 1]]]], {i, 
    4999}, {j, 4999}]] 

Out:140.807 

In:[email protected][c = Drop[a, {100}, {100}]] 

Out:0.093 

In:c===b 

Out:True 

注:對於在早期的崗位使用Drop,我想過用它作爲很好,但是當我檢查文件,沒有建議按照@belisarius和@daniel的建議來完成它。如果在將來的版本中文檔可以按照這個方向進行更新,那將會很有幫助。

+0

您應該檢查**更多信息**在幫助部分。那裏有一些有用的信息。在** Drop **幫助條目中,您只會找到{n} \t元素n:D – 2011-03-14 16:50:45

+0

@belisarius:是的。剛剛看到它。感覺在迷宮中迷失了一點,不過......謝謝。 – Phil 2011-03-14 20:12:57

+0

那種感覺很正常。學習瀏覽幫助系統需要時間,功能清單是_huge_ – 2011-03-14 20:27:41

回答

8

Part切片陣列時直接支持索引的列表。下面的定義利用這一點:

takeOperator[a_?MatrixQ, rows_List, cols_List] := 
    a[[rows, cols]] 

dropOperator[a_?MatrixQ, rows_List, cols_List] := 
a[[##]]& @@ complementaryIndices[a, rows, cols] 

complementaryIndices[a_?MatrixQ, rows_List, cols_List] := 
    Complement @@@ Transpose @ {Range /@ Dimensions @ a, {rows, cols}} 

使用例:

a = RandomInteger[1000, {5000, 5000}]; 
First @ Timing @ takeOperator[a, Range[1, 5000, 2], Range[1, 5000, 2]] 
(* 0.016 *) 

First @ Timing @ dropOperator[a, Range[1, 5000, 2], Range[1, 5000, 2]] 
(* 0.015 *) 
3

您也可以使用明確的範圍,這種方式非常有效。他們可能會提供更多的靈活性。這是你的例子。

a = RandomInteger[1000, {5000, 5000}]; 

Timing[b = Drop[a, {101}, {101}];] 

缺貨[66] = {0.041993,NULL}

Timing[ 
    c = a[[Join[Range[100], Range[102, 5000]], 
    Join[Range[100], Range[102, 5000]]]];] 

缺貨[67] = {0.061991,NULL}

c == b 

缺貨[62] = TRUE

我也建議使用Span,除非是非正式的,我不知道如何讓它在這個環境中工作。

丹尼爾Lichtblau Wolfram Research的

+0

@WReach:謝謝。重點。如果WRI可以在其軟件文檔中提供她選擇的支持,說明使用數學的各種功能,我認爲這將有所幫助。 – Phil 2011-03-14 16:54:13