I have thousands of vectors that represent waveforms, each of those waveforms is representative of a particular sample. I would like to be able to perform an operation on each of those samples and have the output associated with the name of that sample. I have found some information about keys in Mathematica but I can't get them to work correctly. A very simplified example is below. Suppose I have three vectors with 5 elements in each. I could represent this as a matrix in Mathematica as follows:
InputSamples={{1,3,5,6,8}->"SampleA",{7,9,10,45,20}->"SampleB",{90,43,2,1,0}->"SampleC"};
Now suppose I want to do some calculation on each of the samples.
I might choose:
Map[Total,InputSamples]
Now I would want my output to be:
{{SampleA,23},{SampleB,91},{SampleC,136}}
But instead I get:
{{1+SampleA,3+SampleA,5+SampleA,6+SampleA,8+SampleA},{7+SampleB,9+SampleB,10+SampleB,45+SampleB,20+SampleB},{90+SampleC,43+SampleC,2+SampleC,1+SampleC,0+SampleC}}
How can I get this to give the output shown above that I would like or something similar to it?
You get what you ask for with this
InputSamples={{1,3,5,6,8}->"SampleA",{7,9,10,45,20}->"SampleB",{90,43,2,1,0}->"SampleC"};
Map[{#[[2]],Total[#[[1]]]}&,InputSamples]
which instantly returns
{{SampleA,23},{SampleB,91},{SampleC,136}}
Be careful with that and test this method before depending on it
It is not the usual "try to write everything as punctuation characters" style, but this
ruletotal[list_->name_]:={name,Total[list]};
Map[ruletotal,InputSamples]
accomplishes the same thing and might give you some ideas how to do similar tasks in the future.
Some other options
MapAt[Total, InputSamples, {All, 1}]
(* {23 -> "SampleA", 91 -> "SampleB", 136 -> "SampleC"} *)
List ### MapAt[Total, InputSamples, {All, 1}]
(* {{23, "SampleA"}, {91, "SampleB"}, {136, "SampleC"}} *)
InputSamples // Association // KeyMap[Total]
(* <|23 -> "SampleA", 91 -> "SampleB", 136 -> "SampleC"|> *)
InputSamples // Association // KeyMap[Total] // AssociationMap[Reverse]
(* <|"SampleA" -> 23, "SampleB" -> 91, "SampleC" -> 136|> *)
Related
I'm new in system Wolfram Mathematica 9.0 and I want to make table with horizontal approaches. And I had made only vertical ones. Now I will show you:
You did not show the input that produced the undesired output, but I assume it is something like this:
xx = {4, 16};
yy = {3, 5};
TableForm[{{xx}, {yy}}, TableHeadings -> {{"x", "y"}, None}]
To get the output you desire you merely need to leave out the extraneus set of List brackets ({}) around each expression. You can also omit None as this is inferred.
TableForm[{xx, yy}, TableHeadings -> {{"x", "y"}}]
You could also expressly specify the directions with TableDirections:
TableForm[{{xx}, {yy}},
TableHeadings -> {{"x", "y"}},
TableDirections -> {Column, Row, Row}
]
This earlier answer of mine illustrates the way that TableForm formats nested lists:
https://stackoverflow.com/a/5011242/618728
I am trying to calculate a definite integral. I write:
NIntegrate[expression, {x, 0, 1}, WorkingPrecision -> 100]
"expression" is described below. The WorkingPrecision was added in to help with another error.
I get an error:
"NIntegrate::ncvb: NIntegrate failed to converge to prescribed
accuracy after 9 recursive bisections in x near {x} = {<<156>>}.
NIntegrate obtained <<157>> and <<160>> for the integral and error
estimates. >>"
Why am I getting this error for near{x} = {<<156>>} when I am only looking at 0<x<1? And what do the double pointy brackets around the number mean?
The expression is really long, so I think it would be more meaningful to show how I generate it.This is a basic version (some of the exponents I need to be variables, but these are the lowest values, and I still get the error).
F[n_] := (1 - (1 - F[n-1])^2)^2;
F[0] = x;
Expr[n_]:= (1/(1-F[n]))Integrate[D[F[n],x]*x,{x,x,1}];
I get the error when I integrate Expr[3] or higher. Oddly, when I use regular Integrate and then //N at the end, I get a complex number for n=2.
The <<156>> does not mean that the integral is being evaluated at x=156. <<>> is called Skeleton and is used to indicate that a large output was suppressed. From the documentation:
Skeleton[n]
represents a sequence of n omitted elements in an expression printed with Short or Shallow. The standard print form for Skeleton is <<n>>.
Coming to your integral, here's the error that I get:
So you can see that this long number was suppressed in your case (depending on your preferences). The last >> is a link that takes you to the corresponding error message in the documentation.
If you try the advice in the document, which is to increase MaxRecursion, you'll eventually get a new error ::slwcon
So this now tells you that either your WorkingPrecision is too small or that you have a singularity (which is brought on by a small working precision). Increasing WorkingPrecision to 200 gives the following output:
You can look a little further into the nature of your expressions.
num = Numerator#Expr#3;
den = Denominator#Expr#3;
Plot[{num, den}, {x, 0, 1}, WorkingPrecision -> 100, PlotRange -> All]
So beyond 0.7ish, your expression has the potential for serious stability issues, resulting in singularities. It is the numerator rather than the denominator, that requires high precision to converge to the right value.
num /. x -> 0.99
num /. x -> 0.99`100
Out[1]= -0.015625
Out[2]= 1.2683685178049112809413795626911317545171610885215799438968\
06379991565*10^-14
den /. x -> 0.99
den /. x -> 0.99`100
Out[3]= 1.28786*10^-14
Out[4]= 1.279743968014714505561671861369465844697720803022743298030747945923286\
915425027352809730413954909*10^-14
You can see here the difference between the numerator and denominator when you don't have sufficient precision, causing a near singularity.
In Mathematica, I'd like to do something along the lines of:
f[Rational[a_, b_], Rational[c_, d_]] := {a+c, b+d}
But if I evaluate it with expressions of the following form I get the wrong result:
In: f[Rational[50, 100], Rational[4, 10]]
Out: {3, 7}
(* Expected: 54 / 110 -> 27 / 55 *)
Is there any way I can force Mathematica to stop simplifying the expression immediately? I can just do a hold on whatever I pass in, then have the function in question just call ReleaseHold[..] on whatever what was passed in.
This solution is very ugly though, and I don't want to have to do this. I know some functions in Mathematica automatically hold whatever is passed in and delay evaluating it for some reason or another, and I would like to do this here.
In short: How can I force Mathematica to lazily evaluate something being passed into a function without having to manually hold it?
In the standard evaluation procedure, each argument of a function is evaluated in turn. This is prevented by setting the attributes HoldFirst, HoldRest and HoldAll. These attributes make Mathematica "hold" particular arguments in an unevaluated form.
http://reference.wolfram.com/legacy/v5/TheMathematicaBook/PrinciplesOfMathematica/EvaluationOfExpressions/2.6.5.html
e.g.
SetAttributes[yourFunction, HoldFirst]
http://reference.wolfram.com/mathematica/ref/HoldFirst.html
The docs say any auto-Held arguments are automatically evaluated the first time you use them in the function body. However if for some reason you want to continue working with the argument in the Hold form (e.g. if you'd like to do pattern-matching and rewriting on the unevaluated form of the expression), then perhaps you can re-Hold it.
Using the HoldAll attribute ninjagecko mentioned I was able to craft a solution.
There was actually another issue going on that I wasn't able to see immediately. Specifically, my function wasn't pattern matching as I thought it would be.
I thought my initial issue was simply that Mathematica was automatically simplifying my expressions and I needed to lazily evaluate the parameters being passed in for the correct behavior.
In reality, I forgot that there are multiple ways of representing expressions in Mathematica. As a toy example consider the following function which extracts the numerator and denominator of a fraction:
ExtractNumDem[Fraction[a_, b_]] := {a, b}
(* Already incorrect, ExtractNumDem[4 / 100] gives {1, 25} *)
Just adding the HoldAll (Or HoldFirst even) attribute results in another issue:
SetAttributess[ExtractNumDem, HoldAll];
ExtractNumDem[4 / 100] (* Gives ExtractNumDem[4 / 100] *)
The expression 4 / 100 is actually evaluating to Times[4, Power[100, -1]]. To fix this second issue I had to add a definition for fractions that look like that:
ExtractNumDem[Times[a_, Power[b_, -1]] := {a, b}
ExtractNumDem[4/100] (* Now gives {4, 100} *)
My solution to fixing the issue in my original answer applied the same exact principle. Here's some code to actually see the issue I was running into:
ClearAll[ExtractNumDem]
ExtractNumDem[Rational[a_, b_]] := {a, b}
ExtractNumDem[4 / 100]
SetAttributes[ExtractNumDem, HoldAll];
ExtractNumDem[4 / 100]
ExtractNumDem[Times[a_, Power[b_, -1]]] := {a, b}
ExtractNumDem[4/100]
Some types of objects have special input/output formatting in Mathematica. This includes Graphics, raster images, and, as of Mathematica 8, graphs (Graph[]). Unfortunately large graphs may take a very long time to visualize, much longer than most other operations I'm doing on them during interactive work.
How can I prevent auto-layout of Graph[] objects in StandardForm and TraditionalForm, and have them displayed as e.g. -Graph-, preferably preserving the interpretability of the output (perhaps using Interpretation?). I think this will involve changing Format and/or MakeBoxes in some way, but I was unsuccessful in getting this to work.
I would like to do this in a reversible way, and preferably define a function that will return the original interactive graph display when applied to a Graph object (not the same as GraphPlot, which is not interactive).
On a related note, is there a way to retrieve Format/MakeBoxes definitions associated with certain symbols? FormatValues is one relevant function, but it is empty for Graph.
Sample session:
In[1]:= Graph[{1->2, 2->3, 3->1}]
Out[1]= -Graph-
In[2]:= interactiveGraphPlot[%] (* note that % works *)
Out[2]= (the usual interactive graph plot should be shown here)
Though I do not have Mathematica 8 to try this in, one possibility is to use this construct:
Unprotect[Graph]
MakeBoxes[g_Graph, StandardForm] /; TrueQ[$short] ^:=
ToBoxes#Interpretation[Skeleton["Graph"], g]
$short = True;
Afterward, a Graph object should display in Skeleton form, and setting $short = False should restore default behavior.
Hopefully this works to automate the switching:
interactiveGraphPlot[g_Graph] := Block[{$short}, Print[g]]
Mark's concern about modifying Graph caused me to consider the option of using $PrePrint. I think this should also prevent the slow layout step from taking place. It may be more desirable, assuming you are not already using $PrePrint for something else.
$PrePrint =
If[TrueQ[$short], # /. _Graph -> Skeleton["Graph"], #] &;
$short = True
Also conveniently, at least with Graphics (again I cannot test with Graph in v7) you can get the graphic with simply Print. Here, shown with Graphics:
g = Plot[Sin[x], {x, 0, 2 Pi}]
(* Out = <<"Graphics">> *)
Then
Print[g]
I left the $short test in place for easy switching via a global symbol, but one could leave it out and use:
$PrePrint = # /. _Graph -> Skeleton["Graph"] &;
And then use $PrePrint = . to reset the default functionality.
You can use GraphLayout option of Graph as well as graph-constructors to suppress the rendering. A graph can still be visualized with GraphPlot. Try the following
{gr1, gr2, gr3} = {RandomGraph[{100, 120}, GraphLayout -> None],
PetersenGraph[10, 3, GraphLayout -> None],
Graph[{1 -> 2, 2 -> 3, 3 -> 1}, GraphLayout -> None]}
In order to make working easier, you can use SetOptions to set GraphLayout option to None for all graph constructors you are interested in.
Have you tried simply suppressing the output? I don't think that V8's Graph command does any layout, if you do so. To explore this, we can generate a large list of edges and compare the timings of graph[edges];, Graph[edges];, and GraphPlot[edges];
In[23]:= SeedRandom[1];
edges = Union[Rule ### (Sort /#
RandomInteger[{1, 5000}, {50000, 2}])];
In[25]:= t = AbsoluteTime[];
graph[edges];
In[27]:= AbsoluteTime[] - t
Out[27]= 0.029354
In[28]:= t = AbsoluteTime[];
Graph[edges];
In[30]:= AbsoluteTime[] - t
Out[30]= 0.080434
In[31]:= t = AbsoluteTime[];
GraphPlot[edges];
In[33]:= AbsoluteTime[] - t
Out[33]= 4.934918
The inert graph command is, of course, the fastest. The Graph command takes much longer, but no where near as long as the GraphPlot command. Thus, it seems to me that Graph is not, in fact, computing the layout, as GraphPlot does.
The logical question is, what is Graph spending it's time on. Let's examine the InputForm of Graph output in a simple case:
Graph[{1 -> 2, 2 -> 3, 3 -> 1, 1 -> 4}] // InputForm
Out[123]//InputForm=
Graph[{1, 2, 3, 4},
{DirectedEdge[1, 2],
DirectedEdge[2, 3],
DirectedEdge[3, 1],
DirectedEdge[1, 4]}]
Note that the vertices of the graph have been determined and I think this is what Graph is doing. In fact, the amount of time it took to compute Graph[edges] in the first example, comparable to the fastest way that I can think to do this:
Union[Sequence ### edges]; // Timing
This took 0.087045 seconds.
Lets say, that problems are fairly simple - something, that pre-degree theoretical physics student would solve. And student does the hardest part of the task - functional reading: parsing linguistically free form text, to get input and output variables and input variable values.
For example: a problem about kinematic equations, where there are variables {a,d,t,va,vf} and few functions that describe, how thy are dependent of each-other. So using skills acquired in playing fitting blocks where thy fit, you play with the equations to get the output variable you where looking for.
In any case, there are exactly 2 possible outputs you might want and thy are (with working example):
1) Equation for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[True, {d}]
{{d -> (1/2)*(2*t*vf - a*t^2)}}
2) Exact or general numerical value for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[{t == 9.7, vf == -104.98, a == -9.8}, {d}]
{{d->-557.265}}
I am not sure, that I am approaching the problem correctly.
I think that I would probably prefer an approach like
In[1]:= Physics[find_, have_:{}] := Solve[
{d == vf*t - (a*t^2)/2 (* , etc *)} /. have, find]
In[2]:= Physics[d]
Out[2]= {{d -> 1/2 (-a t^2 + 2 t vf)}}
In[2]:= Physics[d, {t -> 9.7, vf -> -104.98, a -> -9.8}]
Out[2]= {{d -> -557.265}}
Where the have variables are given as a list of replacement rules.
As an aside, in these types of physics problems, a nice thing to do is define your physical constants like
N[g] = -9.8;
which produces a NValues for g. Then
N[tf] = 9.7;N[vf] = -104.98;
Physics[d, {t -> tf, vf -> vf, a -> g}]
%//N
produces
{{d->1/2 (-g tf^2+2 tf vf)}}
{{d->-557.265}}
Let me show some advanges of Simon's approach:
You are at least approaching this problem reasonably. I see a fine general purpose function and I see you're getting results, which is what matters primarily. There is no 'correct' solution, since there might be a large range of acceptable solutions. In some scenario's some solutions may be preferred over others, for instance because of performance, while that might be the other way around in other scenarios.
The only slight problem I have with your example is the dubious parametername 'have'.
Why do you think this would be a wrong approach?