4
$\begingroup$

Can anyone show me how to set all matrix rows to variables. For example, I have matrix w={{1,2,3},{3,2,1},{0,0,0}} and I need to set each matrix row to be separate variable that contains the row number of matrix w in its name.

For example, t1={1,2,3} t2={3,2,1} t3={{0,0,0}. Simply it could be done by writing t1=w[[1]] ..., but i have 40 matrices with 200 rows so i need someone to help me do this more efficiently. Variables represents weights in constrained optimization. Thanks in advance.

$\endgroup$
2
  • 1
    $\begingroup$ I have been using Mathematica for a long time, and in my experience what you are asking for indicates a need to re-think your programming strategy. In every situation I can think of, the rows of a matrix of any size can be accessed without assigning each row to a named variable. $\endgroup$
    – m_goldberg
    Commented Oct 2, 2014 at 9:11
  • $\begingroup$ Thanks for comment. I need these rows as variables because i will use them as a vectors in separate optimization problems,and 3 other expressions which analytics should be provide. $\endgroup$
    – Branimir
    Commented Oct 2, 2014 at 9:29

2 Answers 2

4
$\begingroup$

Perhaps this will work for you. Given a symbol, say t, and a matrix, say m, it will define a set of indexed variables t[1], t[2], ..., t[n], bound to the respective rows of m.

SetAttributes[assign, HoldFirst];
assign[name_Symbol, matrix_List] := (
  Clear @ name; 
  Do[t[i] = matrix[[i]], {i, 1, Length@matrix}]
  )

Generate some data.

SeedRandom[42];
m = RandomInteger[99, {5, 4}];
{
  {54, 66, 4, 15}, 
  {6, 3, 95, 32}, 
  {48, 3, 81, 87}, 
  {22, 88, 98, 48}, 
  {44, 36, 71, 46}
}

Test

assign[t, m]
DownValues[t]
{
  HoldPattern[t[1]] :> {54, 66, 4, 15}, 
  HoldPattern[t[2]] :> {6, 3, 95, 32}, 
  HoldPattern[t[3]] :> {48, 3, 81, 87}, 
  HoldPattern[t[4]] :> {22, 88, 98, 48}, 
  HoldPattern[t[5]] :> {44, 36, 71, 46}
}
$\endgroup$
3
$\begingroup$

The code as below can achieve the result that you need.

Clear@t;
mat = RandomInteger[{1, 10}, {20, 4}];
Evaluate[t /@ Range[Length@mat]] = mat

Because of (=)Set has the attribute HoldFirst, I use the function Evaluate to evaluate first before proceeding with Set.

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