Message Boards Message Boards

0
|
1295 Views
|
1 Reply
|
2 Total Likes
View groups...
Share
Share this post:

Assigning elements in a list to variables when the list size is a variable

Hello everyone,

I am still learning a lot about Mathematica. I am trying to understand how I can use mathematica to grab list elements, set them equal to variables and then use the variables in as the bounds for integration. But, as you can see in the code below, the list length is also a variable. So when i'm trying do 30 list elements instead of 40 I would get {NULL} as the out. So I created an IF clause to try and just assign that to zero. Obviously an integral bounded between zeros is zero. This allows the element to still be assigned to the integral but would be excluded from the calculation. How can I create a list of variable length and always have the right number of h_ statements to extract the list elements?
in:

sections = 40;
height = 10;
h = Range[0, sections - 1]*height

Out:

{0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, \
160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, \
300, 310, 320, 330, 340, 350, 360, 370, 380, 390}

In:

h1 = Part[h, 1];
If[h1 == Null, h1, 0, h1]

Out:

0

Same for h2-h39

In:

h40 = Part[h, 40];
If[h40==Null, h40, 0, h40]

Out:

Element 40 DNE
POSTED BY: David Graf

Checking for Equal to Null will not yield True when you think, because when Part goes out of bounds it returns a Part expression not Null.

In[ ]:= Head[Part[h, 40]]

(* During evaluation of In[73]:= Part::partw: Part 40 of {0,10,20,30,40,50,60,70,80,90,<<20>>} does not exist.

Out[ ]= Part *)

Now this version, If is checking for the expression Head returned by Part is the same as the raw symbol name Part.

In[ ]:= Quiet@If[Head[Part[h, 40]] === Part, 0]

(* Out[ ]= 0 *)

What it does not do is pass the value if part extraction was in range. You can make a generic checker function to deal with that at the point of assignment to your variable.

checker=(If[Head[#] === Part, 0, #] &);

Now you can run the extraction result through the checker and suppress the out of bounds message and then make the variable assignment in one line.

In[ ]:= h40 = checker@Quiet[Part[h, 40]]

(* Out[ ]= 0 *)

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract