Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Assigning elements to a matrix

  • To: mathgroup at smc.vnet.net
  • Subject: [mg47389] Re: [mg47358] Assigning elements to a matrix
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Wed, 7 Apr 2004 03:17:19 -0400 (EDT)
  • References: <200404061036.GAA09276@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 6 Apr 2004, at 19:36, Mark Coleman wrote:

> Greetings,
>
> I need to create a series of n x n matrices, in both conventional and
> sparse matrix formats. I have a (large) table of lists, where each list
> is of the form:
>
> {i,j,value}, where {i,j} are the row-column indices and value is the
> corresponding numerical value, i.e., m[[i,j]]=value.
>
> Using this data I need to create an n x n matrix where all the values
> except those specified in my list are 0. I would also like to create a
> similar matrix, this time using Mathematica's built-in SpareMatrix 
> format.
>
> Can anyone suggest a way to do this?
>
> Thanks,
>
> -mark
>
>

Suppose your table looks like this:

t={{1,2,50},{3,4,100},{7,8,500}};

Suppose we want to construct a 20 by 20 sparse array and a matrix of 
the type you have described. We first convert the table into a list of 
rules for construction the array:


s = Append[t /. {(a_)?NumericQ, (b_)?NumericQ,
       (c_)?NumericQ} -> {a, b} -> c, {x_, y_} -> 0]


{{1, 2} -> 50, {3, 4} -> 100, {7, 8} -> 500,
   {x_, y_} -> 0}

Now we create a sparse array using these rules:

A = SparseArray[s, {20, 20}];

We use normal to convert this to a matrix:

Normal[A]


{{0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0}, {0, 0, 0, 100, 0, 0, 0, 0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, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}


Andrzej Kozlowski
Chiba, Japan
http://www.mimuw.edu.pl/~akoz/


  • Prev by Date: Re: problems with FindRoot: what worked with 4.2 does not work with 5.0
  • Next by Date: The same integraton, but different results
  • Previous by thread: Re: Assigning elements to a matrix
  • Next by thread: Re: Assigning elements to a matrix