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

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array. Here a MWE that hopefully shows what my problem is. vars = u@# & /@ Range[3]; cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]), cons}, vars, Integers] The error I get: Part::pkspec1: The expression u[1] cannot be used as a part specification. >> Answer Ok, it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]] . The working MWE would then look like the following: vars = u@# & /@ Range[3]; cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@ R...

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...

What is and isn't a valid variable specification for Manipulate?

I have an expression whose terms have arguments (representing subscripts), like this: myExpr = A[0] + V[1,T] I would like to put it inside a Manipulate to see its value as I move around the parameters. (The goal is eventually to plot it wrt one of the variables inside.) However, Mathematica complains when I set V[1,T] as a manipulated variable: Manipulate[Evaluate[myExpr], {A[0], 0, 1}, {V[1, T], 0, 1}] (*Manipulate::vsform: Manipulate argument {V[1,T],0,1} does not have the correct form for a variable specification. >> *) As a workaround, if I get rid of the symbol T inside the argument, it works fine: Manipulate[ Evaluate[myExpr /. T -> 15], {A[0], 0, 1}, {V[1, 15], 0, 1}] Why this behavior? Can anyone point me to the documentation that says what counts as a valid variable? And is there a way to get Manpiulate to accept an expression with a symbolic argument as a variable? Investigations I've done so far: I tried using variableQ from this answer , but it says V[1...