How to write a long function in Mathematica? Using Notebook as function? - function

I defined some variable in the beginning of a Mathematica notebook and used it afterwards to calculate my results. Now I want to do the same calculation several times for different values of the variable and use the results somewhere. So it would be useful to define a new function with this variable as parameter and the content of my notebook as body. But then I would have to write everything in one single input line and there would be no comfortable way to see the intermediate results.
Is there any good way to deal with this kind of situation?
To clarify what I mean, the a short example:
What I could do is something like this:
In[1] := f[variable_] := (
calculations;
many lines of calcalutions;
many lines of calcalutions;
(* some comments *);
(* finally the result... *);
result
)
And afterwards use this function:
In[1] := f[value1] + f[value2]
But if somebody is interested in the intermediate result of line 1 of function f ("calculations"), then it's necessary to copy the line somewhere else. But then you can't just remove the semicolon at the end of the line to see the line's result.

Using
lc = Notebook[{Cell[
BoxData[\(\(Pause[1]\) ;\)]
, "Input"], Cell[
BoxData[\(\(Print[\(Date[]\)]\) ;\)]
, "Input"], Cell[
BoxData[\(\(Print[
\("variable = ", variable\)] \) ;\)]
, "Input"], Cell[
BoxData[\(result = \(variable^2\)\)]
, "Input"]}, WindowSize ->
{701, 810}, WindowMargins ->
{{Automatic, 149}, {Automatic,
35}}, FrontEndVersion -> "8.0 for Microsoft Windows (64-bit) (October \
6, 2011)", StyleDefinitions ->
"Default.nb"];
Or, if you saved it under longcalc.nb into the same directory as your working notebook, then
lc = Get[FileNameJoin[{SetDirectory[NotebookDirectory[]], "longcalc.nb"}]];
Now, in your working notebook evaluate:
f[var_] := (variable = var;
NotebookEvaluate[NotebookPut[lc], InsertResults -> True]);
f[value1] + f[value2]
will do what you want.

If you do instead
f[variable_] := (
{calculations,
many lines of calcalutions,
many lines of calcalutions,
(* some comments *);
(* finally the result... *);
result}
)
then your function will return a list {ir1,ir2,...,result}, where the ir1 etc are the intermediate results. You could then assign {ir1,ir2,..,re}=f[value] whereupon re would contain the final result while the ir the intermediate results.
Does this work?

you can also do intRes={}; outside function and inside the function dump values into it. Of course this gets tricky if you use parallelization inside your function, or parallelize the whole function.
AppendTo[intRes,ir1];
AppendTo[intRes,ir2];
or
f[variable_] := Block[{output={}},
calculations;
AppendTo[output,ir1];
many lines of calcalutions;
(* some comments *);
AppendTo[output,ir2];
(* finally the result... *);
{output,result}];
and execute as {intRes,result}=f[var]; -- intRes will be a list of interrim results.
If you don't need to retain intermediate results for computation, just see them, then there are much more elegant ways to view what's happenning.
For slower functions, use Monitor[] or Dynamic[] or PrintTemporary[] or ProgressIndicator[] 
Results of these outputs change and/or disappear as the function progresses.
If you want a more permanent record (let's say the function runs really fast), then use Print[] to see intermediate output.
UNLESS of course you need to use intermediate results in computation.

Related

Can I call a function to solve for different variables?

I have a function where I want to solve for many variables separately, do I have to write down the function every time in terms of the other variable?
x,xG,xR
y = e.^tan(x.^2)+cos.^2(x);
yG = e.^tan(xG.^2)+cos.^2(xG);
First you cannot write an expression like cos.^2(x). If x is a single variable (ie x=pi) you could write either cos(x)^2 or cos(x^2). If x is a vector (a column vector might be x=[3;4;pi] and a row vector might be x=[3,4,pi], then you might write cos(x).^2 or cos(x.^2). The role of the period (.) in octave is explained here: https://octave.org/doc/v4.0.3/Arithmetic-Ops.html
Another issue has to do with understanding the difference between an expression: x=e^tanh(y); and a function. The later is a separate chunk of code that can be invoked from anywhere in your program.
Consider this simple example
1;
function y=myfunc(x)
y=exp(tanh(x));
endfunction
## main program
xxx=pi/3;
yyy=myfunc(xxx);
printf('%7.3f %7.3f\n',xxx,yyy)
y=exp(tanh(pi/3))
comments: The '1' in the first line tells Octave that there is more to the script than just the following function: the main program has to be interpreted as well. The function line specifies that inside the function, the input will be called x and the output y, so when my function is called from main, the input is xxx(=pi/2) and the output is yyy. The last line in this tiny script is an expression that does the same thing as the function. Note that since I didn't include a semi-colon at the end of that line the result is printed out
I suggest you play with this for a while, then if you have more questions, ask them in a new question.

How do I allocate a function call to a variable, and how do i count elements in this function

I am new here, and 'only' a mathematician, so please accept these two very simple questions, that keeps troubling me.
In Maple, the function PrintVar(3) returns 3, now I would like to set B=3 in order to use B later. Only, I cannot do this (see picture).
Then, when I want to count the elements in the functioncall above, ie. I would like to do nops(B), but because of my problem above, I try to do nops(PrintVar(3)), but I am not allowed to do this either (maybe since it is not indexable?).
Can anyone help? Thanks a lot.
Sincerely Tomas Medici
Your first problem is that PrintVar() returns NULL because print() returns NULL (it displays its arguments but doesn't return them). You can see this is the case in the output line "C := "
If you want PrintVar to pass through its output so that it is available for assignment, you should write:
PrintVar := proc(e1)
print(e1);
return e1;
end proc;

How to use Eiffel functions?

So I'm just starting to learn Eiffel. One of the first exercises in the book I'm using says to make a function that does base^exp without using ^. I've copied my code below.
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create power(2;3)
printf("2 to the power of 3 is " + answer)
end
power(base : REAL; exp : INTEGER) : REAL
-- computers base raised to the bower of exp without using ^
local
remain : INTEGER
do
remain := exp
if remain = 0 then
result := 1
else
from
until
remain = 0
loop
result := result * result
remain := remain -1
end
end
end
end
How do I use this? Do I need it on the same level as feature{NONE}'s make? I know how I'm calling it is wrong, and I can't find anything in the chapter I just read, or online on how to pass parameters into it or how to use it's results.
There are several issues with the original code:
create is used to create an object, but you are not going to create anything, but to get a result of a computation of the function power by calling it. Therefore the keyword create is not needed.
You are using an entity answer to report the result of evaluation on a screen. However it is not declared anywhere. I believe the proper place would be a local variable declaration section.
The entity answer is not initialized to the result of the function power. This is usually done by an assignment instruction.
Feature arguments are separated by a comma, not by a semicolon.
From the original code it's unclear what is the type of the variable answer. Assuming it matches the type of the function power, before adding it to a string, it needs to be converted to a string. This is done by calling the feature out.
The standard feature for printing a string to a console is print, not printf.
Combining the critical points above, we get
make
-- Run application.
local
answer: REAL
do
answer := power(2, 3)
print ("2 to the power of 3 is " + answer.out)
end
After that the code can be compiled. Now less critical points:
It is a good style to put features to a dedicated feature clauses, so I would add a line like feature -- Basic operations before the feature power.
The implementation of the feature power has at least two problems. I'm not going to detail them here, but would give two hints instead:
by default numeric Result is initialized to 0, this needs to be taken into account for operations that use it without first assigning any other value
even though an argument base is passed to the function power it remains unused in the original version of the code

Is There a Placeholder Variable in Octave?

I'm trying to get the max indexes by row from a matrix. To do this, I'm doing:
[throwaway, indexes] = max(blah, [], 2);
The variable "throwaway," would store values I don't want anymore and would never use, and I don't want to waste memory on it. Is there some way to indicate I don't want anything put into that throwaway variable? Something like undef in Perl, perhaps?
Yes, you can throw away return arguments with ~ for examples if func returns two arguments only v will be available after the following [~, v] = func()

How to evaluate functions in GDB?

I wonder why evaluate function doesn't work in gdb? In my source file I include, when debugging in gdb, these examples are wrong evaluations.
(gdb) p pow(3,2)
$10 = 1
(gdb) p pow(3,3)
$11 = 1
(gdb) p sqrt(9)
$12 = 0
The syntax for calling a function in gdb is
call pow(3,2)
Type
help call
at the gdb prompt for more information.
You need to tell gdb that it will find the return value in the floating point registers, not the normal ones, in addition to give the parameters the right types.
I.e.:
(gdb) p ((double(*)())pow)(2.,2.)
$1 = 4
My guess is that the compiler and linker does some magic with those particular functions. Most likely to increase performance.
If you absolutely need pow() to be available in gdb then you can create your own wrapper function:
double mypow(double a, double b)
{
return pow(a,b);
}
Maybe also wrap it into a #ifdef DEBUG or something to not clutter the final binary.
BTW, you will notice that other library functions can be called (and their return value printed), for instance:
(gdb) print printf("hello world")
$4 = 11
Actually, at least on my LINUX implementation of gcc, many of the math functions are replaced with variants specific to the types of their arguments via some fancy substitutions pulled in by math.h and bits/mathcalls.h (included from within math.h). As a consequence, functions like pow and exp are called instead as __pow or *__GI___exp (your results may vary depending on the types of the arguments and perhaps the particular version).
To identify what exactly the function is that is linked in to my code I put a break at a line where just that function is called, e.g. have a line in my code with b=exp(c);. Then I run in gdb up till that break point and then use the "step" command to enter the call from that line. Then I can use the "where" command to identify the name of the called routine. In my case that was *__GI___exp.
There are probably cleverer ways to get this information, however, I was not able to find the right name just by running the preprocessor alone (the -E option) or by looking at the assembly code generated (-s).
NAME
pow, powf, powl - power functions
SYNOPSIS
#include <math.h>
double pow(double x, double y);
You shouldn't pass an int in the place of a double
call pow( 3. , 2. )
Also, passing a single argument is not enough, you need two arguments just like the function expects
wrong: call pow ( 3. )