2
$\begingroup$

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}};
$\endgroup$
4
  • $\begingroup$ @Kuba Maybe he means i should be a power of two from 1 to n? That would fit with what he has. $\endgroup$ Dec 7, 2015 at 19:42
  • $\begingroup$ 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? $\endgroup$ Dec 7, 2015 at 19:44
  • $\begingroup$ The 4th row is indeed a mistake, thanks for that :) $\endgroup$
    – phytab
    Dec 7, 2015 at 20:21
  • $\begingroup$ Sorry for the confusion with Dynamic, I mean that the size of the matrix should change with n as you mentioned. $\endgroup$
    – phytab
    Dec 7, 2015 at 20:22

2 Answers 2

3
$\begingroup$

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}]]
$\endgroup$
5
  • $\begingroup$ This one has problems if list has a zero in it. $\endgroup$ Dec 7, 2015 at 19:46
  • $\begingroup$ @2012rcampion corrected $\endgroup$
    – glS
    Dec 7, 2015 at 19:53
  • $\begingroup$ 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. $\endgroup$ Dec 7, 2015 at 19:55
  • $\begingroup$ 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 $\endgroup$
    – glS
    Dec 7, 2015 at 19:57
  • $\begingroup$ This is working, thank you very much. $\endgroup$
    – phytab
    Dec 7, 2015 at 21:13
0
$\begingroup$
Manipulator[Dynamic[n], {2, 10,1}]
Dynamic[list2 = list^# & /@ Range[0, n-1]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.