4
$\begingroup$

Consider a function as

f[n_]:=Module[{x,y}, 
x=Table[Sin[i],{i,0,Pi,Pi/(n-1)}];
y=Table[Cos[i],{i,0,Pi,Pi/(n-1)}];
Transpose[{x,y}]
]

Now, this function will work for all the values of n>1. However, for n=1, I want the function to return {1,1}. If I use If-else inside the function, I get the result, but, it gives me the error message as well.

How can I resolve this issue?

$\endgroup$
  • 2
    $\begingroup$ To be structurally consistent, f[1] should be {{1,1}}, i.e., a list of points. To be efficient, f[1]={{1,1}}; f[n_Integer]:={Sin[#], Cos[#]}& /@ Range[0, Pi, Pi/(n-1)] $\endgroup$ – Bob Hanlon Sep 19 '18 at 13:52
  • $\begingroup$ What error? Share the code, which has the problem. $\endgroup$ – Johu Sep 19 '18 at 15:25
3
$\begingroup$
f[n_] := Module[{x, y}, 
         If[n == 1, {1, 1}, 
            x = Table[Sin[i], {i, 0, Pi, Pi/(n - 1)}]; 
            y = Table[Cos[i], {i, 0, Pi, Pi/(n - 1)}]; 
                Transpose[{x, y}]]]

f[1]
(* {1,1} *)
$\endgroup$
  • $\begingroup$ Thanks. It's really a great way. Exactly the kind of solution I was looking for. $\endgroup$ – Majis Sep 19 '18 at 13:04
3
$\begingroup$

Mathematica is an expression rewriting language. Use that (and eliminate unnecessary code):

f[n_] := Transpose[{Table[Sin[i], {i, 0, Pi, Pi/(n - 1)}],
  Table[Cos[i], {i, 0, Pi, Pi/(n - 1)}]}]
f[1] = {1, 1};

When more than one rewrite is possible, Mathematica prefers the one with the more specific trigger, f[1] in this case

$\endgroup$
3
$\begingroup$
ClearAll[f]
f[n_] := Transpose[{Table[Sin[i], {i, n /. {1 -> π / 2, _ :> 0}, π, π/(n - 1)}], 
   Table[Cos[i], {i, 0, π, π/(n - 1)}]}]

f[1]

{{1, 1}}

f[3]

{{0, 1}, {1, 0}, {0, -1}}

$\endgroup$
1
$\begingroup$

This is more efficient.

f[1] = {1, 1};
f[n_?IntegerQ] /; n > 1 := Table[{Sin[i], Cos[i]}, {i, 0, Pi, Pi/(n - 1)}]

Table[f[i], {i, 5}]
{{1, 1}, 
 {{0, 1}, {0, -1}}, 
 {{0, 1}, {1, 0}, {0, -1}}, 
 {{0, 1}, {Sqrt[3]/2, 1/2}, {Sqrt[3]/2, -(1/2)}, {0, -1}}, 
 {{0, 1}, {1/Sqrt[2], 1/Sqrt[2]}, {1, 0}, {1/Sqrt[2], -(1/Sqrt[2])}, {0, -1}}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.