Group Abstract Group Abstract

Message Boards Message Boards

0
|
7.9K Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Syntax for Nested Functions

Posted 11 years ago
POSTED BY: Nick Hare
2 Replies
Posted 11 years ago

To understand your problem, I made small example and set up a function to find the total weight of all balls of a certain type:

In[3]:= SeedRandom[1234](*10 ball types with a different weight each \
between 10 and 50*)
ballWeightsByType = RandomReal[{10, 50}, 10]

Out[4]= {45.0643, 30.8786, 13.4489, 25.1165, 10.4658, 47.0906, \
31.7503, 29.1733, 19.814, 40.3958}

In[5]:= (*random collection of 50 balls identified by their ball type*)

In[6]:= ballsByType = RandomInteger[{1, 10}, 50]

Out[6]= {3, 9, 9, 1, 5, 8, 4, 7, 6, 4, 8, 10, 1, 5, 5, 3, 3, 5, 8, 6, \
9, 3, 3, 7, 8, 3, 6, 3, 1, 3, 8, 10, 6, 7, 8, 1, 10, 6, 8, 8, 8, 10, \
8, 8, 6, 1, 6, 5, 4, 10}

In[7]:= (*get weight of balltype x*)

In[8]:= ballWeight[x_?IntegerQ] := First@Take[ballWeightsByType, {x}]

In[9]:= ballWeight[7]

Out[9]= 31.7503

In[10]:= (*list of {type,weight} of all 50 balls sorted by type*)

In[11]:= lst = SortBy[{#, ballWeight[#]} & /@ ballsByType, First]

Out[11]= {{1, 45.0643}, {1, 45.0643}, {1, 45.0643}, {1, 45.0643}, {1, 
  45.0643}, {3, 13.4489}, {3, 13.4489}, {3, 13.4489}, {3, 
  13.4489}, {3, 13.4489}, {3, 13.4489}, {3, 13.4489}, {3, 
  13.4489}, {4, 25.1165}, {4, 25.1165}, {4, 25.1165}, {5, 
  10.4658}, {5, 10.4658}, {5, 10.4658}, {5, 10.4658}, {5, 
  10.4658}, {6, 47.0906}, {6, 47.0906}, {6, 47.0906}, {6, 
  47.0906}, {6, 47.0906}, {6, 47.0906}, {6, 47.0906}, {7, 
  31.7503}, {7, 31.7503}, {7, 31.7503}, {8, 29.1733}, {8, 
  29.1733}, {8, 29.1733}, {8, 29.1733}, {8, 29.1733}, {8, 
  29.1733}, {8, 29.1733}, {8, 29.1733}, {8, 29.1733}, {8, 
  29.1733}, {8, 29.1733}, {9, 19.814}, {9, 19.814}, {9, 19.814}, {10, 
  40.3958}, {10, 40.3958}, {10, 40.3958}, {10, 40.3958}, {10, 40.3958}}

In[12]:= (*number of balls of type 7*)

In[13]:= Count[lst, {7, _}]

Out[13]= 3

In[14]:= (*weight of all balls of type 6*)

In[15]:= % ballWeight[7]

Out[15]= 31.7503 Null

In[16]:= weightTotalByType[type_?IntegerQ] := 
 Count[lst, {type, _}]*ballWeight[type]

In[17]:= weightTotalByType[7]

Out[17]= 95.2508

In[18]:= (*list of {type,total weight of all balls of type} of all 50 \
balls sorted by type*)

In[19]:= {#, weightTotalByType[#]} & /@ Range[10]

Out[19]= {{1, 225.322}, {2, 0.}, {3, 107.591}, {4, 75.3496}, {5, 
  52.3289}, {6, 329.635}, {7, 95.2508}, {8, 320.906}, {9, 
  59.4419}, {10, 201.979}}
Attachments:
POSTED BY: Erik Mahieu
Posted 11 years ago
POSTED BY: Nick Hare
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard