# How can I create a dynamic Matrix inside a function?

I have a function where a n parameter is handed and a list of values is calculated inside of it. I then need to solve a linear system of equations that require me to construct a n x n matrix where the first row is only 1's the second row is the calculated list in a row and the following rows are this list raised to power i, where i=2,...,n.

Example:

n=4; list={2,3,5,4};
m = {{1, 1, 1, 1}, {2,3,5,4}, {4, 9, 25, 16}, {8,27,125,64}};

• @Kuba Maybe he means i should be a power of two from 1 to n? That would fit with what he has. Commented Dec 7, 2015 at 19:42
• Phytab, by "dynamic" do you mean that you want to use this function inside a Dynamic expression, or do you just mean that the size of the matrix should change when you feed the function a different n? Commented Dec 7, 2015 at 19:44
• The 4th row is indeed a mistake, thanks for that :) Commented Dec 7, 2015 at 20:21
• Sorry for the confusion with Dynamic, I mean that the size of the matrix should change with n as you mentioned. Commented Dec 7, 2015 at 20:22

Define

f[n_,list_] := Table[ list^k, {k,0,n-1} ]


so that f[3,{2,3,4}] produces {{1,1,1},{2,3,4},{4,9,16}}.

If list can contain zeros, use the following instead:

f[n_, list_] :=
Table[If[k == 0, ConstantArray[1, Length@list], list^k], {k, 0,
n - 1}]


or, to avoid to have it do a check at every iteration,

f[n_, list_] := Join[{ConstantArray[1,Length@list]},Table[list^k,{k,1,n-1}]]

• This one has problems if list has a zero in it. Commented Dec 7, 2015 at 19:46
• @2012rcampion corrected
– glS
Commented Dec 7, 2015 at 19:53
• Since you know you're going to have exactly one k == 0 every time, I would have done something like Prepend[Table[list^k, {k, n}], ConstantArray[1, Length@list]] to avoid the If. Commented Dec 7, 2015 at 19:55
• I actually thought of doing it like that, but then found the code with the If more clear. But of course you are right it is useless to have it do the check every time
– glS
Commented Dec 7, 2015 at 19:57
• This is working, thank you very much. Commented Dec 7, 2015 at 21:13
Manipulator[Dynamic[n], {2, 10,1}]
Dynamic[list2 = list^# & /@ Range[0, n-1]]