Re: Beginner: List Indexing and Assignment
- To: mathgroup at smc.vnet.net
- Subject: [mg94511] Re: Beginner: List Indexing and Assignment
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Mon, 15 Dec 2008 07:45:28 -0500 (EST)
On 12/14/08 at 7:41 AM, cjr.list.alias.1 at me.com (C Rose) wrote: >I am moving from another system to Mathematica and have a few simple >questions about indexing and altering lists. I've been able to find >Mathematica equivalents to some of the other system's idioms, but >as a Mathematica neophyte they're not very elegant. I'd be very >grateful if someone could tell me the Mathematica equivalents---or >point me to a suitable Rosetta stone (Google didn't easily turn one >up). >In the other system, I would create a 2x3 matrix using >a = [1 2 3; 4 5 6] >resulting in >[1 2 3] [4 5 6] In Mathematica this would be: In[1]:= a = {{1, 2, 3}, {4, 5, 6}} Out[1]= {{1, 2, 3}, {4, 5, 6}} >and then assign any element of the matrix whose value is greater >than 2 the value -1 using >a(a>2) = -1 >resulting in >[ 1 2 -1] [-1 -1 -1] >I can do this in Mathematica by: >a = ReplacePart[a, Position[a, x_ /; x > 2] -> -1] >but is there a more elegant method? Yes. In[2]:= Clip[a, {0, 2}, {-1, -1}] Out[2]= {{1,2,-1},{-1,-1,-1}} >Another way (in the other system) is to create a logical array: >logical = a>2 >resulting in >[0 0 1] [1 1 1] Here too, Clip could be used. That is In[6]:= Clip[a, {2.5, 2.5}, {0, 1}] Out[6]= {{0,0,1},{1,1,1}}