Group Abstract Group Abstract

Message Boards Message Boards

0
|
12.4K Views
|
4 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Using "If" statement here?

Posted 9 years ago
Attachments:
POSTED BY: David Kirkby
4 Replies

Hi David, your problem stems from the use of symbols for male and female. Mathematica can't know what kind of a value a symbol may aquire down the line, so sex==male is simply not determined. Try evaluating the following:

sex=female;
sex==male
sex===male

As you can see, the second line simply doesn't know if your statement is True or False. The last line (with three equal signs, i.e. SameQ) does what you want because it treats undecided cases as False. However, the cleaner alternative would be to work with strings:

sex="female";
sex=="male"

This way, nothing can go wrong even if you accidentally assign a value to male or female eventually.

POSTED BY: Bianca Eifert

You can also avoid using conditionals and global variables by just putting your coefficients in an association:

coeff =
 <| "male" -> <|"offsetDelayps" -> 55.1, "C0" -> 50.389,  "C1" -> 761.36 , "C2" -> -968.22,  "C3" -> 68.376|>,
  "female" -> <|"offsetDelayps" -> 39.8, "C0" -> 53.004,  "C1" -> 135.167, "C2" ->  95.6305, "C3" -> 30.937|>|>

Then just get the value you need like

In[2]:= coeff["male", "offsetDelayps"]

Out[2]= 55.1


In[3]:= coeff["female", "C3"]

Out[3]= 30.937
POSTED BY: Gustavo Delfino
Posted 9 years ago

Thank you both. I was not aware of the === operator. I was only aware of the = and == operators.

I guess an advantage of the Switch command over the If command, is that if I make a typo, and mean to set the sex to male, but accidentally set it to mole (or some other typo), the variables will not get set, so all the processing will go wrong and it will be obvious there's a problem.

POSTED BY: David Kirkby
Posted 9 years ago

Further to Biancas suggestion to use strings:

In[1]:= sex = "female";

In[2]:= Switch[sex,
  "male",
    offsetDelayps = 55.1;
    C0 = 50.389,
  "female",
    offsetDelayps = 39.8;
    C0 = 53.004
];

In[3]:= offsetDelayps
        C0

Out[3]= 39.8

Out[4]= 53.004
POSTED BY: Hans Milton
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard