Dimensions of a substituted symbol - wolfram-mathematica

Best way to get the Dimension of a till now unknown symbol.
For example:
foo = Dimensions[undefined][[1,1]];
foo /.undefined -> {{1,2},{3,4}}
Theses lines of code do not work. Does anyone know, how to write this correctly?
I have to import the the values by substitutions. 'foo' as a function and 'a' as a parameter is unfortunately no alternative for me.

You have the right idea in your self-answer and I voted for it. However you should be aware that MatrixQ is not as general as you might want. For example a three dimensional tensor will fail it:
tensor = RandomInteger[9, {3, 2, 4}];
MatrixQ[tensor]
False
Dimensions can be used on an expression that is not even a List:
f[f[1, 2], f[3, 3]] // Dimensions
{2, 2}
Further your use of Part is not correct. Note the warning message:
dim[undefined][[1, 1]]
During evaluation of In[106]:= Part::partd: Part specification dim[undefined][[1,1]] is longer than depth of object. >>
dim[undefined][[1, 1]]
There is no part (1, 1) in the output of Dimensions. If you instead use [[1]] you will simply extract undefined from dim[undefined]. Instead you should include the part extraction in the definition of dim, or if you have Mathematica 10+ you can use Indexed.
I propose:
dims[x : _[__], part__: All] := Dimensions[x][[part]]
Now:
dims[undefined] /. undefined -> tensor
{3, 2, 4}
dims[undefined, 1] /. undefined -> tensor
3
dims[undefined, 2] /. undefined -> f[f[1, 2], f[3, 3]]
2
Visit the dedicated Mathematica Stack Exchange site:

I found a possibility:
Need to wrap 'Dimensions'
dim[x_?MatrixQ] := Dimensions[x];
...
foo = dim[undefined][[1,1]];
foo /.undefined -> {{1,2},{3,4}}
This works!

Related

Mathematica syntax with & symbol

I have come across this expression in Mathematica:
oneStep[plus[e1_ , e2_]] := Flatten[{With[{a=e1,b=#},plus[a,b]]&/#oneStep[e2],
With[{a=#,b=e2},plus[a,b]]&/#oneStep[e1]}];
but I cant seem to understand what does this &/ symbol mean in this expression.
Secondly: can this be written in more "human-friendly" way?
The & signifies a pure function (which is kind of like a lambda). Yes, it can be written in a friendlier way. As the linked documentation indicates:
body&
is equivalent to
Function[x,body]
where x is the argument.
The /# is a map (which can also be written in a friendlier way, as you can see from the docs).
To supplement arshajii's answer:
veryLongFunctionName[n_] := n + n/2;
Map[veryLongFunctionName, {1, 2, 3}]
which returns:
{3/2,3,9/2}
is longer than:
Map[# + #/2 &, {1, 2, 3}]
which is longer than:
# + #/2 & /# {1, 2, 3}

Replace a part in a table n times by adding the previus values of each iteration and substructing the initial value

I have the following Nested table
(myinputmatrix = Table[Nest[function, myinputmatrix[[i]][[j]],
myinputmatrix[[i]][[j]][[2]][[2]] +
myinputmatrix[[i]][[j]][[3]][[2]]], {i,
Dimensions[myinputmatrix][[1]]}, {j,
Dimensions[myinputmatrix][[2]]}]) // TableForm
fq[k_?NumericQ] := Count[RandomReal[{0, 1}, k], x_ /; x < .1]
function[x_List] := ReplacePart[
x, {{2, 1} -> x[[2]][[1]] - #1,
{2, 2} -> x[[2]][[2]] + #1,
{3, 1} -> x[[3]][[1]] - #2, {3, 2} ->
x[[3]][[2]] + #2}] &[fq[x[[2]][[1]]], fq[x[[2]][[1]]]];
My problem is that I want to add only the #1 in the bold part above, but not only the new one, I want it to add all #1 for the n times (Nest function times]
If I try the function
function[x_List] := ReplacePart[
x, {{2, 1} -> x[[2]][[1]] - #1, {2, 2} -> #1,
{3, 1} -> x[[3]][[1]] - #2, {3, 2} -> #2}] &[fq[x[[2]][[1]]],
fq[x[[2]][[1]]]];
I am having as a result the last value of fq[k]. I thought of replacing that part in my table with 0 but is not going to work since I am using it in my nested list, also I thought of substricting that part from my initial table but I am not sure which way is the best to do it and if the way I am thinking is the correct one. Can anyone help me?
If I may restate the problem and hopefully clarify the question for myself. At each iteration in the Nest, you want to add not the current (random) output from fq, but the cumulation of the current and all past values of it. But because the random output depends at each iteration on the input matrix, you need to calculate both the random number and the current value of the matrix in the same iteration.
If that hadn't been true you could use Fold.
Restating fq as Sasha suggested EDIT with some type checking to avoid problems with incorrect input:
fq[k_Integer?Positive]:=RandomVariate[BinomialDistribution[k,.1]]
You might want to add some other error checking code. Something like this, depending on your requirements, might do.
fq[0]:= 0;
fq[k_Real?Positive]:=RandomVariate[BinomialDistribution[Round[k],.1]]
You need function to take the random numbers as parameters. EDIT 1 and 2 I have changed the syntax of this function to use the parameters explicitly instead of the original question's anonymous function within a function. This should avoid some syntax errors. Also note that I have used "NumericQ" rather than "Real" as the type for the rv1 and rv2 parameters, because they can be integers at the start of the Nest iteration.
function[x_List, rv1_?NumericQ, rv2_?NumericQ] := ReplacePart[
x, {{2, 1} -> x[[2]][[1]] - rv1, {2, 2} -> rv1,
{3, 1} -> x[[3]][[1]] - rv2, {3, 2} -> rv2}]
And then pass the current random number as a local constant using With to a Nest function that works on a list containing your matrix and the cumulation of the random variates. I have used myoutputmatrix because I really don't like the idea of rewriting existing expressions all the time. That's just me. Now, the one other thing is that you need to set n, the number of iterates. I've set it to 5 but you can make this a parameter in a function if you want (see below).
(myoutputmatrix = Table[ First[Nest[With[{rv=fq[#1[[1]][[2]][[1]] ]},
{function[#1[[1]],rv, rv+#1[[2]] ],rv+#1[[2]] }]&,
{ myinputmatrix[[i]][[j]], 0 }, 5]],
{i, Dimensions[myinputmatrix][[1]]}, {j,
Dimensions[myinputmatrix][[2]]}]) // TableForm
The First is there because in the end you only want the matrix, not the cumulation of the random variates.
outputmatrix[input_List, n_Integer?Positive] /;
Length[Dimensions[input]] == 4 :=
Table[First[
Nest[With[{rv = fq[#1[[1]][[2]][[1]]]}, {function[#1[[1]], rv,
rv + #1[[2]]], rv + #1[[2]]}] &, {input[[i]][[j]], 0}, n]],
{i, Dimensions[input][[1]]}, {j, Dimensions[input][[2]]}]
outputmatrix[myinputmatrix, 10] // TableForm
EDIT I have checked this now and it runs, but note that you can get negative numbers in the output, which is not what you want, I don't think.

Mathematica Table function

I'm running a Table function which will take too much time to complete.
I wanted to know if there's a way to retrieve the results computed so far.
The proposed solution
Here is a version of Table that is Abort-able and will keep the intermediate results collected so far. It is a modified version of the solution posted here.
ClearAll[abortableTable];
SetAttributes[abortableTable, HoldAll];
abortableTable[expr_, iter__List] :=
Module[{indices, indexedRes, sowTag},
SetDelayed ##
Prepend[Thread[Map[Take[#, 1] &, List ## Hold ### Hold[iter]],
Hold], indices];
indexedRes =
If[# === {}, #, First##] &#Last#Reap[
CheckAbort[Do[Sow[{expr, indices}, sowTag], iter], {}], sowTag];
AbortProtect[
Map[First,
SplitBy[indexedRes,
Table[
With[{i = i}, Function[Slot[1][[2, i]]]],
{i, Length[Hold[iter]] - 1}]],
{-3}]]];
It should be able to take the same iterator specification as Table.
How it works
Here is how it works. The first statement (SetDelayed ##...) "parses" the iterators, assuming that they are each of the form {iteratorSymbol_,bounds__}, and assigns the list of iterator variables to the variable indices. The construction with Hold is needed to prevent possible evaluation of iterator variables. There are many ways to do this, I used just one of them. Here is how it works:
In[44]:=
{i, j, k} = {1, 2, 3};
Prepend[Thread[Map[Take[#, 1] &, List ## Hold ###
Hold[{i, 1, 10}, {j, 1, 5}, {k, 1, 3}]], Hold], indices]
Out[45]= Hold[indices, {i, j, k}]
Using SetDelayed ## the-above will then naturally produce the delayed definition of the form indices:={i,j,k}. I assigned the values to indices i,j,k to demonstrate that no unwanted evaluation of them happens when using this construct.
The next statement produces a list of collected results, where each result is grouped in a list with the list of indices used to produce it. Since indices variable is defined by delayed definition, it will evaluate every time afresh, for a new combination of indices. Another crucial feature used here is that the Do loop accepts the same iterator syntax as Table (and also dynamically localizes the iterator variables), while being a sequential (constant memory) construct. To collect the intermediate results, Reap and Sow were used. Since expr can be any piece of code, and can in particular also use Sow, a custom tag with a unique name is needed to only Reap those values that were Sown by our function, but not the code it executes. Since Module naturally produces (temporary) symbols with unique name, I simply used a Module - generated variable without a value, as a tag. This is a generally useful technique.
To be able to collect the results in the case of Abort[] issued by the user interactively or in the code, we wrap the Do loop in CheckAbort. The code that is executed on Abort[] ({} here) is largely arbitrary in this approach, since the collection of results is anyway done by Sow and Reap, although may be useful in a more elaborate version that would save the result into some variable provided by the user and then re-issue the Abort[] (the functionality not currently implemented).
As a result, we get into a variable indexedRes a flat list of the form
{{expr1, {ind11,ind21,...indn1}},...,{exprk, {ind1k,ind2k,...indnk}}
where the results are grouped with the corresponding index combination. We need these index combinations to reconstruct the multi-dimensional resulting list from a flat list. The way to do it is to repeatedly split the list according to the value of i-th index. The function SplitBy has this functionality, but we need to provide a list of functions to be used for splitting steps. Since the index of i-th iterator index in the sublist {expr,{ind1,...,indn}} is 2,i, the function to do the splitting at i-th step is #[[2, i]]&, and we need to construct the list of such functions dynamically to feed it to SplitBy. Here is an example:
In[46]:= Table[With[{i = i}, Function[Slot[1][[2, i]]]], {i, 5}]
Out[46]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[2, 5]] &}
The With[{i=i},body] construct was used to inject the specific values of i inside pure functions. The alternatives to inject the value of i into Function do exist, such as e.g.:
In[75]:=
Function[Slot[1][[2, i]]] /. Map[List, Thread[HoldPattern[i] -> Range[5]]]
Out[75]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[2, 5]] &}
or
In[80]:= Block[{Part}, Function /# Thread[Slot[1][[2, Range[5]]]]]
Out[80]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[ 2, 5]] &}
or
In[86]:= Replace[Table[{2, i}, {i, 5}], {inds__} :> (#[[inds]] &), 1]
Out[86]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[ 2, 5]] &}
but are probably even more obscure (perhaps except the last one).
The resulting nested list has a proper structure, with sublists {expr,{ind1,...,indn}} being at level -3 (third level from the bottom). By using Map[First,lst,{-3}], we remove the index combinations, since the nested list has been reconstructed already and they are no longer needed. What remains is our result - a nested list of resulting expressions, whose structure corresponds to the structure of a similar nested list produced by Table. The last statement is wrapped in AbortProtect - just in case, to make sure that the result is returned before the possible Abort[] fires.
Example of use
Here is an example where I pressed Alt+. (Abort[]) soon after evaluating the command:
In[133]:= abortableTable[N[(1+1/i)^i],{i,20000}]//Short
Out[133]//Short= {2.,2.25,2.37037,2.44141,<<6496>>,2.71807,2.71807,2.71807}
It is almost as fast as Table:
In[132]:= abortableTable[N[(1+1/i)^i,20],{i,10000}]//Short//Timing
Out[132]= {1.515,{2.0000000000000000000,2.2500000000000000000,<<9997>>,2.7181459268252248640}}
In[131]:= Table[N[(1+1/i)^i,20],{i,10000}]//Short//Timing
Out[131]= {1.5,{2.0000000000000000000,2.2500000000000000000,<<9997>>,2.7181459268252248640}}
But it does not auto-compile while Table does:
In[134]:= Table[N[(1+1/i)^i],{i,10000}]//Short//Timing
Out[134]= {0.,{2.,2.25,2.37037,2.44141,<<9993>>,2.71815,2.71815,2.71815}}
One can code the auto-compilation and add it to the above solution, I just did not do it since it will be a lot of work to do it right.
EDIT
I rewrote the function to make some parts both more concise and easier to understand. Also,
it is about 25 % faster than the first version, on large lists.
ClearAll[abortableTableAlt];
SetAttributes[abortableTableAlt, HoldAll];
abortableTableAlt[expr_, iter : {_Symbol, __} ..] :=
Module[{indices, indexedRes, sowTag, depth = Length[Hold[iter]] - 1},
Hold[iter] /. {sym_Symbol, __} :> sym /. Hold[syms__] :> (indices := {syms});
indexedRes = Replace[#, {x_} :> x] &# Last#Reap[
CheckAbort[Do[Sow[{expr, indices}, sowTag], iter], Null],sowTag];
AbortProtect[
SplitBy[indexedRes, Array[Function[x, #[[2, x]] &], {depth}]][[##,1]] & ##
Table[All, {depth + 1}]
]];
Unfortunately no. If you want to do something like lst=Table[f[i],{i,1,10000}] so that if aborted you still have results, you could do
Clear[lst2];
lst2 = {};
(Do[lst2 = {lst2, f[i]}, {i, 1, 10000}];
lst2=Flatten[lst2];) // Timing
which, for undefined f, takes 0.173066s on my machine, while lst = Table[f[i], {i, 1, 100000}] takes roughly 0.06s (ie, Table it is 3 times faster at the expense of not being interruptible).
Note that the obvious "interruptible" solution, lst = {};
Do[AppendTo[lst, f[i]], {i, 1, 100000}] takes around 40s, so don't do that: use linked lists and flatten at the end, like in my first example (however, that will break if f[i] returns a list, and more care is then needed).
Another solution is to export results of intermediate computations to a running log file as described in this answer by WReach (see the "File-backed In-memory Approach" section). With this you will newer loose results of intermediate computations and will always be able to investigate what is computed so far.
P.S. I think usage of Monitor as suggested in this recent Mathematica tip on twitter is also useful in such cases:
Monitor[Table[Integrate[1/(x^n + 1), x], {n, 20}],
ProgressIndicator[n, {1, 20}]]

Leaving values for options unevaluated in Mathematica

I'm having some problems with writing a function that takes options. One of the option values is a function. I one to get at this value but keep it unevaluated. I tried every single thing I could possibly think of but nothing worked so far.
Basically, to illustrate this is what I tried:
SetAttributes[Foo, HoldRest];
Options[Foo] = {Blah -> None}
Foo[x_, OptionsPattern[]] :=
Module[{blah},
blah = OptionValue[Automatic, Automatic, Blah, Hold];
.
.
.
Then when I have:
func[a_, b_, c_] := a + b + c;
I'd like to be able to call Foo with:
Foo[2, Blah -> func[1, 2, 3]]
And have the "blah" variable (inside Foo) to be unevaluated, i.e. blah = func[1, 2, 3].
Thanks for all the help in advance!
Edit:
For reasons that are too long to elaborate, I cannot use RuleDelayed (:>). I'm trying to write a function that will be in a package, used by other people that don't really know Mathematica, so they would have no clue what :> is. Using rules (->) for specifying options and their values is the standard way and they familiar with that.
So to further illustrate, let's say that I'm trying to write a number generator function that takes a function that generates the actual number as one of it's options:
Options[GenerateNumbers] = {GeneratorFunction -> None};
GenerateNumbers[n_, OptionsPattern[]] :=
Module[{func},
func = OptionValue[GeneratorFunction];
Table[func, {n}]
]
]
Now, if I called this function with values as follows:
GenerateNumbers[5, GeneratorFunction -> RandomReal[10]]
It would return a list of 5 numbers that are the same, since RandomReal[10] gets evaluated once and not at every iteration of Table. I want to prevent this. The problem is more complicated but it's along these lines.
Thanks!
Use a name for the OptionsPattern and then wrap the captured sequence object with a List and an Unevaluated. A very minimal way of capturing the right-hand side for Blah is:
SetAttributes[Foo, HoldRest]; Options[Foo] = {Blah -> None};
Foo[x_, opts : OptionsPattern[]] :=
Module[{blah},
blah = OptionValue[Foo, Unevaluated[{opts}], Blah, Hold];
blah]
Testing it out:
In[2]:= Foo[x, Blah -> (1 + 1)]
Out[2]= Hold[1 + 1]
Why don't you use RuleDelayed?
Foo[2, Blah :> func[1, 2, 3]]
In this case blah=Hold[func[1, 2, 3]] as expected.
Your usage of the options is a little strange. If you want to pass some expression wrapped in Hold, why not wrap it in Hold when passing, like Blah->Hold[func[1,2,3]]? Anyway, assuming this simple definition for Foo:
Foo[x_, OptionsPattern[]] :=
Module[{blah},
blah = OptionValue[Automatic, Automatic, Blah, Hold];
blah
],
you can accomplish what you want by passing an option with RuleDelayed rather than Rule:
In[7]:= func[a_, b_, c_] := a + b + c;
In[8]:= Foo[2, Blah :> func[1, 2, 3]]
Out[8]= Hold[func[1, 2, 3]]
HTH
Edit:
If you don't want Hold wrapped around, here is one way to get rid of it:
In[25]:=
ClearAll[setDelayedHeld];
SetAttributes[setDelayedHeld, HoldFirst];
setDelayedHeld[lhs_, Hold[rhs_]] := lhs := rhs
In[28]:=
Clear[Foo];
Foo[x_, OptionsPattern[]] :=
Module[{blah},
setDelayedHeld[blah, OptionValue[Automatic, Automatic, Blah, Hold]];
OwnValues[blah]]
In[30]:= Foo[2, Blah :> func[1, 2, 3]]
Out[30]= {HoldPattern[blah$1018] :> func[1, 2, 3]}
I return OwnValues for blah to show that it was assigned func[1,2,3] without evaluating the latter - if this is what you want.

"Select any" in Mathematica

Does mathematica have something like "select any" that gets any element of a list that satisfies a criterion?
If you just want to return after the first matching element, use the optional third argument to Select, which is the maximum number of results to return. So you can just do
Any[list_List, crit_, default_:"no match"] :=
With[{maybeMatch = Select[list, crit, 1]},
If[maybeMatch =!= {},
First[maybeMatch],
default]
Mathematica lacks a great way to signal failure to find an answer, since it lacks multiple return values, or the equivalent of Haskell's Maybe type. My solution is to have a user-specifiable default value, so you can make sure you pass in something that's easily distinguishable from a valid answer.
Well, the downside of Eric's answer is that it does execute OddQ on all elements of the list. My call is relatively costly, and it feels wrong to compute it too often. Also, the element of randomness is clearly unneeded, the first one is fine with me.
So, how about
SelectAny[list_List, criterion_] :=
Catch[Scan[ If[criterion[#], Throw[#, "result"]] &, list];
Throw["No such element"], "result"]
And then
SelectAny[{1, 2, 3, 4, 5}, OddQ]
returns 1.
I still wish something were built into Mathematica. Using home-brew functions kind of enlarges your program without bringing much direct benefit.
The Select function provides this built-in, via its third argument which indicates the maximum number of items to select:
In[1]:= Select[{1, 2, 3, 4, 5}, OddQ, 1]
Out[1]= {1}
When none match:
In[2]:= Select[{2, 4}, OddQ, 1]
Out[2]= {}
Edit: Oops, missed that nes1983 already stated this.
You can do it relatively easily with Scan and Return
fstp[p_, l_List] := Scan[ p## && Return## &, l ]
So
In[2]:= OddQ ~fstp~ Range[1,5]
Out[2]= 1
In[3]:= EvenQ ~fstp~ Range[1,5]
Out[3]= 2
I really wish Mathematica could have some options to make expressions evaluated lazily. In a lazy language such as Haskell, you can just define it as normal
fstp p = head . filter p
There's "Select", that gets all the elements that satisfy a condition. So
In[43]:= Select[ {1, 2, 3, 4, 5}, OddQ ]
Out[43]= {1, 3, 5}
Or do you mean that you want to randomly select a single matching element? I don't know of anything built-in, but you can define it pretty quickly:
Any[lst_, q_] :=
Select[ lst, q] // (Part[#, 1 + Random[Integer, Length[#] - 1]]) &
Which you could use the same way::
In[51]:= Any[ {1, 2, 3, 4, 5}, OddQ ]
Out[51]= 3

Resources