Message Boards Message Boards

GROUPS:

Print a single list using the following function?

Posted 3 months ago
694 Views
|
3 Replies
|
3 Total Likes
|

I want to print a list from a function but It gives me 4 lists. I think I shouldn't use Print[] function.

Here is the code:

alista = {{2, 1}, {4, 4}, {7, 5}, {10, 5}, {12, 5}};
alist3a = {};
fnk[n_] :=
 Which[n == 1, Do[
   alist2a = {(alista[[k, 1]] + 
        alista[[k + 1, 1]])/(2), (alista[[k, 2]] + 
        alista[[k + 1, 2]])/(2)}
   ;
   AppendTo[alist3a, alist2a] && Print[Sort[Join[alista, alist3a]]]
   , {k, 1, Length[alista] - 1}],
  n == 2, Do[
   alist2a = {alista[[i, 
        1]] + (-alista[[i, 1]] + alista[[i + 1, 1]])/(3), 
     alista[[i, 2]] + (-alista[[i, 2]] + alista[[i + 1, 2]])/(3)}
   ;
   AppendTo[alist3a, alist2a] && Print[Sort[Join[alista, alist3a]]]
   , {i, 1, Length[alista] - 1}];
  Do[
   alist3aa = {alista[[i, 
        1]] + (-alista[[i, 1]] + 
         alista[[i + 1, 1]])/(3) + (-alista[[i, 1]] + 
         alista[[i + 1, 1]])/(3), 
     alista[[i, 
        2]] + (-alista[[i, 2]] + 
         alista[[i + 1, 2]])/(3) + (-alista[[i, 2]] + 
         alista[[i + 1, 2]])/(3)};
   AppendTo[alist3a, alist3aa] && Print[Sort[Join[alista, alist3a]]]
   , {i, 1, Length[alista] - 1}]]
fnk[1]

The output is

{{2,1},{3,5/2},{4,4},{7,5},{10,5},{12,5}}

{{2,1},{3,5/2},{4,4},{11/2,9/2},{7,5},{10,5},{12,5}}

{{2,1},{3,5/2},{4,4},{11/2,9/2},{7,5},{17/2,5},{10,5},{12,5}}

{{2,1},{3,5/2},{4,4},{11/2,9/2},{7,5},{17/2,5},{10,5},{11,5},{12,5}}

The requested output is the last row in the printed list.

{{2,1},{3,5/2},{4,4},{11/2,9/2},{7,5},{17/2,5},{10,5},{11,5},{12,5}}
3 Replies

You get that output with a different programming style:

Riffle[alista, MovingAverage[alista, 2]]

You get that output with a different programming style:

Riffle[alista, MovingAverage[alista, 2]]
Posted 3 months ago

It is printing with each iteration of the Do[]. You could remove the &&Print[...] from each case and use it at the end of the Which[] like

Which[...]&&Print[...]

Then calling the function with fnk[x]; would print what you want.

Note that you can't use the list like l1=fnk[2] if you use Print[]. I would suggest using Block[] and the Sort[...] from your Print[Sort[...]] and initializing local variables so you could do something like the following without using Print

fnk[alista_,n_]:=Block[
                   {alist3a={},alist2a,alist3aa},
                   Which[...];
                   Sort[...]
             ]

Clear[] those variable names which you have used in your function, and you can evaluate it as follows (and easily use the results list if needed):

alist1= {{2, 1}, {4, 4}, {7, 5}, {10, 5}, {12, 5}};
fnk[alist1,1]
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