Group Abstract Group Abstract

Message Boards Message Boards

0
|
5K Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Constructing For loop with If condition with function assign

Posted 10 years ago

Hi, I tried to do simple code using Mathematica which i'll use later for my mathematics calculation but it seems not like what I expected

For[n=1, n<12, n++,        
        If[OddQ[n],     
        Z[n_] := n * i,    
            Z[n_] := n * k ]]  

I expected that the result would give :

Z[1] = i    
Z[2] = 2k    
Z[3] = 3i    
Z[4] = 4k

and so on

However, the results are

Z[1] = i    
Z[2] = 2i    
Z[3] = 3i    
Z[4] = 4i 

and so on..

anybody can help? Thanks

POSTED BY: Updating Name

The code you posted have many issues. May be it was a cut/paste problem. Also important to know the difference between = vs. :=. Also avoid UpperCaseSymbols and function names in Mathematica. They can conflict with Mathematica own symbols.

I think what you want is

ClearAll[i, k];
z = Last@Reap@Table[If[OddQ[n], Sow[n i], Sow[n k]], {n, 1, 12}]
(*{{i, 2 k, 3 i, 4 k, 5 i, 6 k, 7 i, 8 k, 9 i, 10 k, 11 i, 12 k}}*)

Or you can Sow the If itself

 z = Last@Reap@Table[Sow@If[OddQ[n], n i, n k], {n, 1, 12}]
POSTED BY: Nasser M. Abbasi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard