I have a large number of matrices having equal numbers of columns but different numbers of rows. Say, their order is n X 4, Where n can be any integer between 1000 to 1050. How to tell Mathematica to add 1050-n dummy rows to a matrix of order n X 4 so that all of them have same order of 1050 X 4. The dummy column could be anything, say {a, a, a, a}.
5 Answers
Let's say t
contains matrices, whose dimensions are:
Dimensions /@ t
{{10, 4}, {13, 4}, {11, 4}, {10, 4}}
Here I am assuming that I am going to make every matrix a {15,4} dimension matrix. Create dummy arrays: (replace 15 with 1050 in your case)
darrays = ConstantArray[{1, 2, 3, 4}, 15 - Dimensions[#][[1]]] & /@ t
result = MapThread[Join[#1, #2] &, {t, darrays}];
Dimensions /@ result
{{15, 4}, {15, 4}, {15, 4}, {15, 4}}
You may use SparseArray
and Band
.
For a matrix m
MatrixForm[m = Partition[Range[16], 4]]
Then add 2 rows with SparseArray
MatrixForm@SparseArray[m, {6, 4}]
Band
can be used to place m
in the new matrix. For example, to start m
at the second row.
MatrixForm@SparseArray[Band[{2, 1}] -> m, {6, 4}]
The default value can be changed with the third argument of SparseArray
.
Hope this helps.
Clear["Global`*"]
$Version
(* "12.3.1 for Mac OS X x86 (64-bit) (June 19, 2021)" *)
nbrRows = 10; (* = 1050 in your actual problem *)
Format[a[m_, n_]] := Subscript[a, Row[{m, , n}]]
SeedRandom[123];
matrices
represents your original matrices
Row[MatrixForm /@
(matrices = Table[n = RandomInteger[{3, nbrRows}];
Array[a, {n, 4}], 3])]
newMatrices
are the padded matrices with the specified Dimensions
Row[MatrixForm /@ (newMatrices = (PadRight[#, nbrRows, pad] & /@
matrices) /. pad -> ConstantArray[a, 4])]
m = Partition[Range[16], 4]
ArrayReshape[m, {4,0}+Dimensions[m],a]//TeXForm
$$ \left( \begin{array}{cccc} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \\ a & a & a & a \\ a & a & a & a \\ a & a & a & a \\ a & a & a & a \\ \end{array} \right) $$
m//ArrayReshape[#, {4,0}+Dimensions[m]]&//TeXForm
$$ \left( \begin{array}{cccc} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ \end{array} \right) $$
filler = Function[{matrices, len, fill},
With[{
n = Length[matrices],
cols = Last@Dimensions@First@matrices
},
PadRight[matrices, {n, len, cols}, fill]]]
E.g., filler[matrices,1050,a]
.
PadRight
. $\endgroup$n = 8; PadRight[RandomReal[{0, 1}, {n, 4}], {1050, Automatic}, a]
$\endgroup$