Skip to main content

matrix - While loop (or alternative) to generate list of random submatrices satisfying condition


I'm trying to generate a list of random submatrices with matrix norm 0.1, however I'm getting stuck; currently my code looks like this, where I run over a while loop.


Randnum:= RandomReal[NormalDistribution[0, 1]];                             
Randz := Randnum + I*Randnum;
Randmat[n_] := Table[Randz, {n}, {n}];
Randuni[n_] := Orthogonalize[Randmat[n]];

fbfmatricestest={};

tbtmatricestest={};
epsilontest={};
normepsilontest={};
While[Length[normepsilontest]<=1,
(
(*Generate a random matrix*)
a=Randuni[4];
(*Take the 3x3 submatrix out*)
b=Take[a,{1,3},{1,3}];
(*generate the epsilon matrix*)

\[Epsilon]=Simplify[ConjugateTranspose[b].b -{{1,0,0},{0,1,0},{0,0,1}}];
(*n\[Epsilon] measures gives the norm of each submatrix*)
n\[Epsilon]=Norm[\[Epsilon]];
If[
Abs[n\[Epsilon]-0.1]<0.01,
(
AppendTo[fbfmatricestest,a];
AppendTo[tbtmatricestest,b];
AppendTo[epsilontest,\[Epsilon]];
AppendTo[normepsilontest, n\[Epsilon]]

)
]
)
]

How can I efficiently generate this random list? I read that Reap and Sow might be able to generate a bunch and then collect those which satisfy a condition, but I feel this may end up taking longer than the procedure above I am trying to get working. Many thanks!



Answer



Explanations


I will present a method which relies on p-form calculation of matrix norms, a method that is already implemented in Mathematica.


We generate a random $n_1\times n_2$ complex matrix as follows:



ClearAll[randomMatrix];
randomMatrix[n1_, n2_] := RandomComplex[{-1 - I, 1 + I}, {n1, n2}];
randomMatrix[n_] := RandomComplex[{-1 - I, 1 + I}, {n, n}];

We calculate all possible rectangular submatrices by considering all possible positions for upperleft corner of submatrix and all possible row and column lengths:


ClearAll[possibleSubMatrices];
possibleSubMatrices[n1_, n2_] := possibleSubMatrices[n1, n2] = Flatten[Table[{leftTop1, leftTop2, rowLength, columnLength}, {leftTop1, n1 - 1}, {leftTop2, n2 - 1}, {columnLength, 1, n1 - leftTop1}, {rowLength, 1, n2 - leftTop2}], 3];

Then, given any matrix, following code gives all possible submatrices:


ClearAll[listSubMatrices];

listSubMatrices = Function[input, With[{n1 = Dimensions[input][[1]], n2 = Dimensions[input][[2]]},
Function[input[[#[[1]] ;; #[[1]] + #[[4]], #[[2]] ;; #[[2]] + #[[3]]]]] /@ possibleSubMatrices[n1, n2] ]];

For example,


With[{matrix = Array[a, {4, 3}]},
{MatrixForm[matrix], MatrixForm /@ listSubMatrices[matrix]}
] // TeXForm


$$ \left\{\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ a(4,1) & a(4,2) & a(4,3) \\ \end{array} \right),\left\{\left( \begin{array}{cc} a(1,1) & a(1,2) \\ a(2,1) & a(2,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ a(2,1) & a(2,2) & a(2,3) \\ \end{array} \right),\left( \begin{array}{cc} a(1,1) & a(1,2) \\ a(2,1) & a(2,2) \\ a(3,1) & a(3,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ \end{array} \right),\left( \begin{array}{cc} a(1,1) & a(1,2) \\ a(2,1) & a(2,2) \\ a(3,1) & a(3,2) \\ a(4,1) & a(4,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ a(4,1) & a(4,2) & a(4,3) \\ \end{array} \right),\left( \begin{array}{cc} a(1,2) & a(1,3) \\ a(2,2) & a(2,3) \\ \end{array} \right),\left( \begin{array}{cc} a(1,2) & a(1,3) \\ a(2,2) & a(2,3) \\ a(3,2) & a(3,3) \\ \end{array} \right),\left( \begin{array}{cc} a(1,2) & a(1,3) \\ a(2,2) & a(2,3) \\ a(3,2) & a(3,3) \\ a(4,2) & a(4,3) \\ \end{array} \right),\left( \begin{array}{cc} a(2,1) & a(2,2) \\ a(3,1) & a(3,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ \end{array} \right),\left( \begin{array}{cc} a(2,1) & a(2,2) \\ a(3,1) & a(3,2) \\ a(4,1) & a(4,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ a(4,1) & a(4,2) & a(4,3) \\ \end{array} \right),\left( \begin{array}{cc} a(2,2) & a(2,3) \\ a(3,2) & a(3,3) \\ \end{array} \right),\left( \begin{array}{cc} a(2,2) & a(2,3) \\ a(3,2) & a(3,3) \\ a(4,2) & a(4,3) \\ \end{array} \right),\left( \begin{array}{cc} a(3,1) & a(3,2) \\ a(4,1) & a(4,2) \\ \end{array} \right),\left( \begin{array}{ccc} a(3,1) & a(3,2) & a(3,3) \\ a(4,1) & a(4,2) & a(4,3) \\ \end{array} \right),\left( \begin{array}{cc} a(3,2) & a(3,3) \\ a(4,2) & a(4,3) \\ \end{array} \right)\right\}\right\} $$




Note that we ignore $1x1$ submatrices.


As the next step, we define


ClearAll[chooseCorrectNorms];
chooseCorrectNorms[list_List, normAverage_, error_] := With[{norms = Norm[#, 1] & /@ list}, Pick[list,
UnitStep[(norms - normAverage - error) (normAverage - error - norms)], 1]];

which eliminates matrices of undesired norms. See that we are using Norm[list,p] command to calculate matrix norm. Also, note that we are using vectorized commands Pick and UnitStep instead of conditional If and friends for better performance.


Now, our last command is this:


ClearAll[try];

try[normAverage_, error_] := With[{matrix = randomMatrix[4]}, {matrix, chooseCorrectNorms[listSubMatrices[matrix], normAverage, error]}];

It generates a random $4x4$ matrix, find all submatrices, and eliminate those with undesired norms.


Now, we simply need to run try command again and again until we hit a nonempty list.


Example


DeleteCases[Table[try[.1,.5],10^3],{_,{}}]
(* {{{{0.670769 - 0.179352 I,
0.583875 - 0.0771007 I, -0.0528683 + 0.221524 I,
0.312784 - 0.899022 I}, {-0.201839 + 0.0572823 I,
0.0601396 + 0.102979 I,

0.572871 + 0.221715 I, -0.352286 + 0.510435 I}, {0.150507 -
0.124843 I, -0.379535 - 0.142305 I,
0.0565353 - 0.22504 I, -0.390374 + 0.823681 I}, {0.664221 +
0.375659 I, 0.913889 - 0.853969 I, -0.923382 + 0.855335 I,
0.110999 + 0.149893 I}}, {{{-0.201839 + 0.0572823 I,
0.0601396 + 0.102979 I}, {0.150507 - 0.124843 I, -0.379535 -
0.142305 I}}}}} *)

which means the random matrix




$$\left( \begin{array}{cccc} 0.670769\, -0.179352 i & 0.583875\, -0.0771007 i & -0.0528683+0.221524 i & 0.312784\, -0.899022 i \\ -0.201839+0.0572823 i & 0.0601396\, +0.102979 i & 0.572871\, +0.221715 i & -0.352286+0.510435 i \\ 0.150507\, -0.124843 i & -0.379535-0.142305 i & 0.0565353\, -0.22504 i & -0.390374+0.823681 i \\ 0.664221\, +0.375659 i & 0.913889\, -0.853969 i & -0.923382+0.855335 i & 0.110999\, +0.149893 i \\ \end{array} \right)$$



has the submatrix



$$\left( \begin{array}{cc} -0.201839+0.0572823 i & 0.0601396\, +0.102979 i \\ 0.150507\, -0.124843 i & -0.379535-0.142305 i \\ \end{array} \right)$$



which has the matrix norm $0.52459$.


Performance considerations


I wrote above example to show that the code works and finds solutions for high enough error margins. However, it needs more trials for lower error margins.


The code works relatively fast in the sense that it generates $10,000$ $4\times 4$ random complex matrices and checks all their submatrices under 3 seconds on may laptop. However, the low error margin means we need a lot more trials and the required time increases as we can see:



DeleteCases[Table[try[.1,.01],10^3],{_,{}}]//Timing
(* {0.274255,{}} *)

DeleteCases[Table[try[.1,.01],10^4],{_,{}}]//Timing
(* {2.70209,{}} *)

DeleteCases[Table[try[.1,.01],10^5],{_,{}}]//Timing
(* {27.9623,{}} *)

One immediate thing that we can do is to parallelize the computations. The simplest thing to do is to use ParallelTable instead of Table. On my laptop which has 2 cores, this seems to be a nice performance improvement:



DeleteCases[ParallelTable[try[.1,.01],10^5],{_,{}}]//Timing
(* {2.21016,{}} *)

DeleteCases[ParallelTable[try[.1,.01],10^6],{_,{}}]//Timing
(* {30.9441,{}} *)

With higher number of cores, it will surely be more manageable.


Final Comments


The way we are doing the calculation here is quite ugly: We brute force generate random matrices and see if they satisfy a very selective condition. As the probability that they satisfy that condition is low, we need to generate lots of matrices to find one, which is simply a waste of resources.


A more proper way to do this is to generate $2\times 2$, $2\times 3$, or $3\times 3$ matries with required form and then embed it into a random $4\times 4$ matrix. For example,



Timing[chooseCorrectNorms[ParallelTable[randomMatrix[2],10^3],.1,0.01]]
(*{0.02439,{}}*)

generates random $2\times 2$ matrices and check their norm directly. This approach is clearly faster, though I still fail to find a solution:


Timing[chooseCorrectNorms[ParallelTable[randomMatrix[2], 10^4], .1, 0.01]]

(* {0.119413, {}} *)

Timing[chooseCorrectNorms[ParallelTable[randomMatrix[2], 10^5], .1, 0.01]]


(*{1.0971, {}}*)

Comments

Popular posts from this blog

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...