Message Boards Message Boards

5
|
41481 Views
|
122 Replies
|
37 Total Likes
View groups...
Share
Share this post:

[WSG21] Daily Study Group: Wolfram Language Basics

A new study group for Wolfram Language Basics begins Monday, Feb 15, 2021!

Join this three-week study group to build or refresh your knowledge of the Wolfram Language. We will start slow but try to cover a broad variety of topics. No prior experience in Wolfram Language is needed to join this study group. We will provide study materials along with self-learning exercises so you can review topics on your own beyond the study group sessions.

Sign up here: https://wolfr.am/T4GiU9ch

122 Replies

Looking forward to seeing you and @Arben K co-leading this study group!

POSTED BY: Jamie Peterson

Hi Ulf, A good rule of thumb is to use Evaluate when you want to ensure all symbolic processing of the expression has been completed before Plot (which has HoldAll attribute) tries to substitute numerical values for x in the function.

In this particular example, using Evaluate to first replace f with the InterpolatingFunction from the NDSolve solution is ideally the right way to proceed. However, if we substitute x with a numeric value and then replace f with another function, it still works fine (replacement of f is not affected by the numeric value of x).

The order in which evaluation proceeds is more important in the example quoted a few comments back in this thread:

Plot[Evaluate[Normal[Series[Sin[x], {x, 0, 10}]]], {x, -2 Pi, 2 Pi}]

Here you absolutely want to finish the symbolic evaluation of Normal[Series[Sin[x], {x, 0, 10}]]] before numeric values of x are passed to it. So you need to force the evaluation using Evaluate.

Hi Artin, Let's make sure we understand what the pattern {x,y_,z} represents. It stands for a list with at least two elements (x and z) and any sequence of zero or more Wolfram Language expressions in between. It will match each of the following expressions:

{begin,end}
{begin, middle, end}
{begin, middle1, middle2, end}

In the first case, y___ matches nothing between begin and end. In the second case y___ matches middle between begin and end. In the third case y___ matches the sequence of the two expressions middle1-middle2 between begin and end.

In[1]:= MatchQ[#, {x_, y___, z_}] & /@ {{begin, end}, {begin, middle, 
   end}, {begin, middle1, middle2, end}}
Out[1]= {True, True, True}

If ___ matches a sequence of length more than one, then the sequence will be represented by a Sequence object. Sequence automatically splices its argument into any function with which it is used. So you get a Sequence for y___:

In[2]:= {begin, middle1, middle2, end} /. {x_, y___, z_} :> y
Out[2]= Sequence[middle1, middle2]

When you replace y with the sequence in the Power expression Power[y,z] with:

Power[y, z] /. y -> Sequence[middle1, middle2]

what you end up with is:

In[4]:= Power[middle1, middle2, z]
Out[4]= middle1^middle2^z

because Power[x,y,z. ...] is taken to be Power[x,Power[y,z,...]]

Now back to your question, how can we get {two^four, three^four}? The following would be one way to do it:

In[17]:= SequenceCases[{one, two, three, four}, {x_, y_, z_} :> y^z, Overlaps -> True]
Out[17]= {two^three, three^four}

Remember arguments to a function are evaluated before they are passed to the function unless you set its attribute using something like Hold*.

Head[Sequence[two,three]] 

is really seen as

Head[two,three] 

and we know from the documentation Head[expr,h] wraps the result with h. Head of two is Symbol which is therefore wrapped with three.

You can see the Head of a Sequence by holding it unevaluated.

In[27]:= Head[Unevaluated[Sequence[two, three]]]
Out[27]= Sequence

Thank you Abrita for the detail and clear explanation.

However the code doesn't give the required result (two^four, three^four)

SequenceCases[{one, two, three, four}, {x_, y_, z_} :> y^z, Overlaps -> True]

However this works as expected:

{one, two, three, four} /. {first_, middle___, last_} :> {middle}^
  last

The "Wolfram Language basics" study group begins today. See you there!

Happy to be a part of this study session cohort!

POSTED BY: Steph Macurdy

For all the new folks who attended Study Group today: Feel free to try Wolfram One (https://www.wolfram.com/wolfram-one/) to open up the notebook we shared with you.

Posted 3 years ago

Alternative for first 500 digits of π

N[Pi, 500] // RealDigits // First

While Table[Sin[x],{x,1,10}] and Plot[Sin[x],{x,1,10}] use the same x range, the points used by Plot are chosen so that the plot is "smooth".

tablePoints = Table[Sin[x], {x, 1, 10}];

plot = Plot[Sin[x], {x, 1, 10}];
plotPoints = Cases[plot, Line[p_] :> p, All] // First;

ListPlot[{plotPoints, tablePoints}, 
 PlotStyle -> {Automatic, Directive[PointSize[Medium], Red]}]

enter image description here

POSTED BY: Rohit Namjoshi
Posted 3 years ago

Great talks by Abrita and Arben. How can I find my way to the quiz? Thanks, Roger

POSTED BY: Roger Shifrin

Hi larawag,

Ah, I see what you mean. That is indeed a difficult general problem to solve, and I've run into it myself in the past. After some searching, I've found something that seems to work... it still needs a bit of simplification (with Simplify or FullSimplify), but it ought to do what you want, and thee discussion surrounding it provides some insight as to why this is a nontrivial problem:

https://mathematica.stackexchange.com/questions/3822/can-i-simplify-an-expression-into-form-which-uses-my-own-definitions

Using: FullSimplify[expr // TermErsetzung[2 s == \[Xi] (-1 + s^2), s], Assumptions -> \[Xi] > 0] I was able to get pretty close to your desired output (really, just requiring breaking up the sum. Hopefully this is helpful!

Arben

POSTED BY: Arben Kalziqi
Posted 3 years ago

Thank you Arben for bringing this link to my attention (and of course for the quick and on-target reply...).

POSTED BY: lara wag

You're welcome, Larawag—glad to be able to help!

Arben

POSTED BY: Arben Kalziqi

Thanks Arben, The german term Ersetzung attacted me as I read German. That's a useful function. John.

POSTED BY: John Burgers

Thank you. Sorry about that - we'll get these edited.

That was clever Arben, and teaches me how to diagnose. Thanks for asking forward. John

POSTED BY: John Burgers
Posted 3 years ago

I figured it out.

someText = {"State A", "State A1", "State A2", "State B", "Random Test"};
stringToAction[x_] := Switch[x
   , Condition[x, StringMatchQ[x, "State A*"]], actionA
   , "State B", actionB
   , _, "State Unrecognized" <> x
   ];
Map[stringToAction, someText]
POSTED BY: Updating Name

Thank you for reporting the error. Not sure why RotateLeft crept in there. It should simply be:

BarChart[data2[[All, 2]], ChartLabels -> Placed[data2[[All, 1]], Below, Rotate[#, Pi/2] &]]

The idea was to rotate the labels by 90 degrees to avoid crowding at the bottom of the chart.

Hi Arben, Abrita, and others,

I have the following questions about about editing stylesheet and converting a Notebook into a PDF:

  1. I want to modify the existing stylesheet (for example, JournalArticle under Article menu in Stylesheet) and place this newly created stylesheet under the same sub-menu Article. Is there any way or option to assign the file location of the new stylesheet when I save it?

  2. The attached stylesheet includes a lenthy table. When I convert this notebook into a PDF file, some portion of the table is cut off. Is there any way to control the size of the table in the notebook, so that it can be reprinted or converted in its entirety.

  3. The MS word processor has a Preview menu that allows to anticipate the printed version of the work. Is there any way to visualize the text-heavy notebook similarly before either printing or converting?

Thanks.

POSTED BY: Hee-Young Shin
Posted 3 years ago

Abrita, thank you very much for yesterday's very interesting and enlightening lesson.

On slide 14 of "Tips and Tricks" an example was shown regarding machine precision and arbitrary precision. Is there any way that WL's output will indicate when the machine precision solution will be wrong?

If one doesn't have a hint that the solution is wrong, one could be lulled into a false sense of security and thus assume wrong results to be correct. Especially since the command N[...] is more intuitive for a user than N[..., 10], where the latter command provides the more accurate result, see attachment.

As a side topic: Using Mathematica, how can you prove (or confirm otherwise) which of the two results is the correct one?

I attached a picture of your example, which I have adapted a bit to make this issue a clearer. After playing around for a while, I found the a illustration which shows roughly where the solution breaks down. This point seems to be independent of the number of valid digits (here the n-digit precision was set to n=10), and so, it originates from the first term (term with machine precision), right?

Attachment

Attachment

Attachments:
POSTED BY: lara wag

Thank you very much Arben, Your absolutely correct. Not having personal audio files I reached into the web to a site offering "example" mp3 files, a couple of seconds long. Never occurred to me it would be copyright protected. Good that we learned about Databins this week and so it's pretty clear to me what "ExampleData/car.mp3" means. Now curious about how to find out what's all in "ExampleData". Probably another question to post.

Your example code suggested I improve the codec with FFmpeg ?? something or other so I changed to, Automate[Plot[Sin[k x], {x, 0, 2 [Pi]}, PlotRange -> {-1, 1}], {{k, .1, "Wavenumber"}, .1, 5}]. which worked. Then switched back to Manipulate which then also worked. Hmmm. something got intialized by Automate.

All the best Arben p.s. see my next post, Boo looks the size of a black panther on my screen !! Nice cat. and I just loved, hearing Boo meow, and how polite you were to announce the moments of attending to Boo.

POSTED BY: John Burgers

Hi John, Glad to know you found the series helpful.

To set the text size one option is to set the Magnification for Global Preferences from the Options Inspector. I have mine set to 1.5 and its helpful even on a small screen. You will find detailed instructions here: https://support.wolfram.com/25214. This will enlarge all content in all notebooks. I believe the same approach should work for setting the WindowSize as well.

Posted 3 years ago

We ran into some issues with a couple of examples during today's session. Here are possible resolutions to those issues:

  • First 500 digits of Pi: ResourceFunction["NthDigit"][\[Pi], #] & /@ Range[500]
  • Example of using lists in the same way (domain of input values) in two different Wolfram Language functions: Table[Sin[x],{x,1,10}] and Plot[Sin[x],{x,1,10}]

Here is the example of processing the DNA sequence from the BRCA 1 gene (with the nucleotides as chemical entities instead of just string characters):

Counts[Characters[Entity["Gene", {"BRCA1",  {"Species" -> "HomoSapiens"}}]["ReferenceSequence"]] /. 
     {"A" -> Entity["Chemical", "Adenine"], 
      "T" ->  Entity["Chemical", "Thymine"], 
      "G" ->  Entity["Chemical", "Guanine"], 
      "C" -> Entity["Chemical", "Cytosine"]}]
POSTED BY: Updating Name
Posted 3 years ago

Thank you for showing the replacement to turn the strings into entities in the nucleotides example. Ron

POSTED BY: Rongoetz

Good day, everyone!

I've got a small noobie question. I declare a function using Module to hide local variable x. And I expect x to be local. But when I check what is x with question mark, it is says, x is global.

Are things to be that way? What don't I understand?

enter image description here

POSTED BY: Fedor Sumkin

Hi Fedor, The syntax coloring is giving us a hint that the "?" is not working on the local symbol x but on the global symbol (since x appears black, not green). So it is correctly informing us of the status of the global "x". Perhaps you could try replacing "?x" with Information[x] which would ensure the right "x" was being used for information. enter image description here

Posted 3 years ago

In slide 31 of the notebook for the second day, it looks like there is a small error in coding for the function FixMatrix. The code works fine for square matrices (as in the examples given), but not for general matrices, because the mapping over the column numbers is taken over the row numbers instead. It can be fixed by replacing

Range[Length[mat]] (*the list of row numbers*) 

by either

Range[Length[Transpose[mat]]] 

or

Range[Last[Dimensions[mat]]] (*the list of column numbers*)

Ron Goetz

POSTED BY: Rongoetz

Thanks Ron, for the catching the issue and sharing the resolution.

May I get a link to the first session on Monday? I have the 2nd one from Tuesday and 3rd one from Thursday. Thank you

POSTED BY: Michael Lyda

Hi Michael, We're re-sending the link to you via email.

Posted 3 years ago

I can't seem to download the data1D.dat data1D2.dat files in the data folder.

POSTED BY: Rongoetz

Hi Ron, Selecting the two .dat files and clicking on Download from the "... Actions" menu should allow you to download a zip containing the two data files.

enter image description here

Hi Roger, The link to the quiz that was shared in the study group session today, will alsol be included in the next reminder email for the webinar.

With the free basic plan, I am unable to find a way to upload the notebooks you have shared with the Study Group into Wolfram One/Cloud. enter image description here Have I missed something?

Thank you. Yeu Wen

Posted 3 years ago

That was what I did, among other variations, but nothing worked in Chrome. I switched to a different browser and had no trouble. I'm guessing there is a way of telling Chrome it's OK to download DAT files, but I couldn't find it on a first pass through the settings.

POSTED BY: Updating Name
Posted 3 years ago

Good morning/evening,

In exercise 3.7 if I use the following code (in version 12.0) I generate the error General::ivar: -12.5659 is not a valid variable:

Manipulate[
 Plot[{Sin[x], Normal[Series[Sin[x], {x, 0, n}]]}, {x, -4 \[Pi], 
   4 \[Pi]}, PlotRange -> {-10, 10}], {n, 1, 23, 2}]

In order to fix it I have to force the evaluation of the series expansions as:

Manipulate[
 Plot[{Sin[x], 
   Normal[Series[Sin[x], {x, 0, n}]] // Evaluate}, {x, -4 \[Pi], 
   4 \[Pi]}, PlotRange -> {-10, 10}], {n, 1, 23, 2}]

Does anyobody experience the same? Most importantly, does anybody know why the first code snippet is not a valid Wolfram statement?

Thanks

POSTED BY: Fabio Alcaro

Plot has attribute HoldAll and tries to evaluate the function Normal[Series[...]] only after assigning specific numerical values to x. As you have shown in the resolution, in this case we need to force the symbolic evaluation of Series[Sin[x],{x,0,someInteger}] to obtain the power series expansion for Sin[x] before trying to substitute numeric values for x. This is why the following is unable to plot:

Plot[Normal[Series[Sin[x], {x, 0, 10}]], {x, -2 Pi, 2 Pi}]

But using Evaluate resolves the issue:

Plot[Evaluate[Normal[Series[Sin[x], {x, 0, 10}]]], {x, -2 Pi, 2 Pi}]
Posted 3 years ago

Thanks Abrita for the explanation!

POSTED BY: Fabio Alcaro
Posted 3 years ago

From time to time I consider equations like "f(x) = some right-hand side". To investigate this kind of equations, I want to transform them by a rule like \xi = x/some factor, say \xi = x/a. (Typically, x and a have the same dimension and thus \xi is dimensionless.) Therefore, I want Mathematica to find and collect all quotients of x/a and replace them with \xi.

Replacing "(1 + x)^6 /. x -> 3 - a" is quite simple and standard. But the reverse way doesn't seem to work, does it? Unfortunately I didn't find any hints in the reference.

So, how do you deal with this symbolic issue?

POSTED BY: lara wag

Hi Larawag,

I'm not sure that I understand what you're asking—if I do understand correctly, then that seems to work:

In[1]:= f[x_]:=2+Sin[x/a]
In[2]:= f[x]/.x/a->ξ
Out[2]:= 2+Sin[ξ]

Are you asking for something different? If so, could you provide an explicit sample input and the expected output?

Thanks!

Arben

POSTED BY: Arben Kalziqi
Posted 3 years ago

Thank you very much for your quick reply, Arben!

You hit my point exactly, but "of course" I have more difficult examples in mind:

Example 1:

In[1]:= (-((4 s^2)/(-1 + s^2)^2) + (2 s)/(-1 + s^2))/(
  2 (1 + (4 s^2)/(-1 + s^2)^2)^(3/2)) + 
  Sin[(2 s)/(-1 + s^2)] /. (2 s)/(-1 + s^2) -> \[Xi]

Out[1]= (-((4 s^2)/(-1 + s^2)^2) + \[Xi])/(
 2 (1 + (4 s^2)/(-1 + s^2)^2)^(3/2)) + Sin[\[Xi]]

My expected output looks like this

(-\[Xi]^2 + \[Xi])/(2 (1 + \[Xi]^2)^(3/2)) + Sin[\[Xi]]

Example 2: In the example above I have already helped Mathematica, of course it would be nice if the task could also be solved when one is one step further away - i.e. if this equation had to be substituted:

-((2 s^2)/((-1 + s^2)^2 (1 + (4 s^2)/(-1 + s^2)^2)^(
   3/2))) + s/((-1 + s^2) (1 + (4 s^2)/(-1 + s^2)^2)^(3/2)) + 
 Sin[(2 s)/(-1 + s^2)] /. (2 s)/(-1 + s^2) -> \[Xi]

So you could summarize that I would like to have a) an automatism (or a workaround or a strategy) that collects the terms as desired (see Example 2) and b) also considers powers of the variable (see Example 1).

POSTED BY: lara wag
Posted 3 years ago
sol = NDSolve[{f''[x] + f'[x] + 8 f[x] == 0, f[0] == 0, f'[0] == 1}, 
f, {x, 0, 10}] ;

Plot[Evaluate[f[x] /. sol], {x, 0, 10}, PlotRange -> All]

Expressions like Plot[Evaluate[f[x] /. sol] are given in the Help-examples of NDSolve

In the solution for Exercise 5.8 Plotting a result from NDSolve the following expression is given

Plot[f[x] /. sol, {x, 0, 10}, PlotRange -> All]

Both expressions give the same diagram.

In which cases i have to use Plot[Evaluate[f[x] /. sol] and in which cases i have to use Plot[f[x] /. sol] ?

POSTED BY: Ulf Schmidt

Good day, everyone.

I was doing some exploring recently. And tried to use a web-camera image as a good source of data. I am using Mathematica 12.1 on my Raspberry Pi 4 with an USB webcam attached.

What I don't understand is, when I try to grab an image, I get an error. I did the documentation digging and found out, that there were special variables \ $ImagingDevice and \$ImagingDevices, that select and represent the devices, the image is grabbed from. I checked, what device was used, and without chaning anything the image grab started working as expected. I reproduced this behaviour several times and made a screenshot.

What was I doing wrong? Thanks in advance, F.

enter image description here

POSTED BY: Fedor Sumkin

When will the Advanced Programming recording become available to rewatch?

POSTED BY: Steph Macurdy

Yesterday's Study Group recording is now available: https://wolfr.am/TyQ6Qt0q

POSTED BY: Jamie Peterson

Reminding our Study Group participants that the New in Version 12.2 webinar starts in less than 1 hour, at noon CST. Today's topics include the latest enhancements in visualization, the new area of bio-sequence computation, and new functionality for Wolfram Notebooks and working with code.

Sign up for the webinar here: https://wolfr.am/TyPQmtDD

POSTED BY: Jamie Peterson

Hi Fedor, Unfortunately I do not have a better explanation other than a guess that the code behind $ImagingDevices (or FindDevices[] or other similar functions) triggered an initial handshake with the device or camera. Seems like initially DeviceOpen or DeviceRead was failing under the hood behind CurrentImage. Once the camera device was recognized, CurrentImage started working.

We do have a Raspberry Pi group on community: https://community.wolfram.com/content?curTag=raspberry%20pi Perhaps you will find other folks there who may have seen and tried some troubleshooting for similar issues?

Executing the packed array timing example I didn't get the order of magnitude faster execution. Attached file shows the timing I got. Anyone have an idea why the timing stayed the same? Thanks in advance.

Attachments:
POSTED BY: John Burgers
Posted 3 years ago

Exercise 7.7 states "...load your package to introduce the rules for the function fib..."

How exactly do i load the package fib as generated by exercise 7.7?

Needs["..."] or Get["..."] are not working properly.

POSTED BY: Ulf Schmidt

Hi Arben, see code snippet attached. Question why I didn't see an order of magnitude faster timing. John

Attachments:
POSTED BY: John Burgers

Can you check the directory where you saved the package?

It should either be listed with the directories shown by evaluating

$Path

or you will have to use the full path with Get

<<"/Full/Path/to/folder/and/package/fibPackage.wl"

Hi Abrita,

There are minor typos in the 2nd quiz that I would like to draw your attention:

  1. Problem 3 C) NIntegrate[f[n], {n, 0, 1}]. The last closing square bracket is missing;

  2. Problem 8 "Which is these functions ---?" -> "Which one of the following functions ---- ?" or simply "Which function ----?"

Thanks.

POSTED BY: Hee-Young Shin

Hi John,

Thanks for the notebook. My suspicion is that Accumulate is packing the array automatically—if it is packable—and that Accumulate was updated some time between the creation date of this original notebook and the present. See the linked notebook, where I change a 0 to a 0. to preclude the possibility of packing, and get (suspiciously...) a 10x slowdown. I can't be sure that that's because the array is no longer "packable", but that's my best guess.

I've asked through an internal channel for some clarification on this, and will update you if I learn anything!

https://www.wolframcloud.com/obj/arbenk/Published/05%20Numerics%20PackArray%20Timing%20(test).nb

POSTED BY: Arben Kalziqi
Posted 3 years ago

Unfortunately it appears that the free basic plan does not allow file upload or the option to download and install the Wolfram Desktop. You would have to subscribe to a paid plan for those options.

You could download and install a trial version of Mathematica to open the shared notebooks https://www.wolfram.com/mathematica/trial/

POSTED BY: Updating Name

Hello everyone! I was doing the exercises of the seventh session but I can't find the file "weather.dat". Could you please share it? Thanks in advance.

POSTED BY: Angel Mosquera

The term "indices" is used often in Mathematica. As is "levelspec". Is there a documentation page which defines the meaning or interpretation of these words, or indeed the terminology of Mathematica?

For instance, in the guide/ElementsOfLists we learn that indices may be different than positions. In the help for Cases, we learn that Cases uses standard levelspec definition where n is interpreted to mean all parts of an expression specified by n indices.

Putting these thoughts together, does this mean that a list element is addressed by it's {row, column, ...} and each element of this address list is an index, the plural of which defines the use of "indices". And that level spec is the depth of these indices ie. levelspec at depth p = Length[ {1,2,3,..,p, ...}] or element of a list at index {1,2,3,..,p, ...} ?

Is the use of n in Cases[v,test,n] where n=2 to mean all combinations of { ...x,y,...}, where x,y means any adjacent pair of 2 indices.

Not sure if the last paragraph can be understood, if not don't dwell on it.

Thanks, John

POSTED BY: John Burgers

I have two questions. One is a question about Switch. The second is about how to use the documentation for Switch.

I have a string, and need to perform completely different actions based upon the value of the String. Here are example strings.... "State A1" "State A2" "State A3" "State A...." "State B" "State C"

I would like to have a Switch Statement with three clauses, something like: Switch[myInput,StringMatchQ[#,"State A*"],actionForA,"State B",actionForB,"State C",actionForC]

2 Questions:

Question 1: How to fix the above statement?

Question 2: How to learn from the documentation how to fix the above statement. For instance, StringMatchQ apparently is not a "form." But "form" is not defined anywhere in the Switch documentation. Searching the docs for the wolfram language on form gives a lot of results on how to "form" output, but not on what switch is expecting as a "form". There is a link in the Switch statement to "Conditionals" which is very hopeful, but again, in the Conditionals documentation "form" is used, but never defined. Can you teach me how to fish?

POSTED BY: John Hoffman
Posted 3 years ago

Hi John,

I would use Which rather than Switch for this

string = "State A2"

Which[
 string == "State A1",
 Print[string],
 string == "State A2",
 Print[StringReverse@string],
 string == "State A",
 Print[string]]
(* 2A etatS *)

Using Switch

Switch[string,
 "State A1",
 Print["State A1"],
 "State A2",
 Print["State A2"],
 "State A",
 Print["State A"]]
POSTED BY: Rohit Namjoshi

Rohit, you didn't answer my question. Perhaps I didn't state it clearly. I'd like a single Switch/Which clause to capture all the strings, "State A1" … "State A3" I can't figure out how to do that. By my reading of the documentation, I assumed a "form" of StringMatchQ[#,"State A*"] would work. It did not. What should I do differently to make that work?

POSTED BY: John Hoffman
Posted 3 years ago

You are right, I completely misunderstood the question. Sorry about that.

The body of a pure function that does not use Function must end in &.

StringMatchQ[#, "State A*"] & /@ {"State A1", "State Ab", "State A1 zz", "State a"}
(* {True, True, True, False} *)
POSTED BY: Rohit Namjoshi

Rohit, you again misunderstood the issue. The issue is to put this into the switch statement. Here I take your answer, and put it into the switch statement. It fails. (In my original test on my notebook, I had the &, I just missed it when I typed it in here. This time I copied/pasted.) The first three entries in the output list should be "actionA" but they are all unrecognized by the switch statement.

someText = {"State A", "State A1", "State A2", "State B", "Random Test"};
stringToAction[x_] := Switch[x
   , StringMatchQ[#, "State A*"] &, actionA
   , "State B", actionB
   , _, "State Unrecognized" <> x
   ];
Map[stringToAction, someText]

{"State UnrecognizedState A", "State UnrecognizedState A1", "State UnrecognizedState A2", actionB, "State UnrecognizedRandom Test"}

POSTED BY: John Hoffman
Posted 3 years ago

Getting there .... :-)

someText = {"State A", "State A1", "State A2", "State B", "Random Test"};

stringToAction[string_] :=
 Which[
  StringMatchQ[string, "State A*"],
  "actionA",
  StringMatchQ[string, "State B*"],
  "actionB",
  True,
  "State Unrecognized: " <> string]

stringToAction /@ someText
(* {"actionA", "actionA", "actionA", "actionB", "State Unrecognized: Random Test"} *)

stringToAction2[string_] :=
 Switch[
  StringCases[string, "State " ~~ x_ ~~ ___ :> x],
  {"A"}, "actionA",
  {"B"}, "actionB",
  _, "State Unrecognized: " <> string]

stringToAction2 /@ someText
(* {"actionA", "actionA", "actionA", "actionB", "State Unrecognized: Random Test"} *)

If you have to deal with more than a handful of states and actions, rather than generating a long Switch or Which manually, considering using a list of rules and maybe Dispatch.

POSTED BY: Rohit Namjoshi
Posted 3 years ago

What about this input? Are there never multiple B states?

someText = {"State A", "State A1", "State A2", "State B1", "Random Test"};
POSTED BY: Rohit Namjoshi
Posted 3 years ago

Exercise 6.4 becomes more interesting if you replace the one approximate real coefficient, 7.5, by its exact rational equivalent, 15/2. Then the symbolic roots of the polynomial are given as root objects, and the suggested solutions to the exercise for finding the real solutions mostly fail without modification (one of them still works). In particular, root objects don't match either pattern _Real or _Complex.

Ron Goetz

POSTED BY: Rongoetz

Note to File : Working with Data
Slide 10 of 21 Visualise the total sales for each title: RotateLeft[ ... ] shifts the labels one to the left of the correct sales bar.

John Burgers

POSTED BY: John Burgers

Hi Angel, I added weather.dat to the data folder. Sorry about that.

Hi John, It may be helpful to view a list (or really any expression in the Wolfram Language) as a tree. You can even visualize it using the function TreeForm. For example here is a nested list with Dimensions {4, 3, 2} and its TreeForm representation:

words = {{{"anisotropy", "mugful"}, {"organist", 
     "socialization"}, {"worsening", "feeder"}}, {{"mawkishness", 
     "polity"}, {"technique", "cathartic"}, {"sore", 
     "zenith"}}, {{"aniline", "linguine"}, {"brutality", 
     "boutonniere"}, {"nonintervention", "venation"}}, {{"zirconium", 
     "compartmentalization"}, {"pentathlon", 
     "servitor"}, {"immovability", "blah"}}};

Dimensions[words]
{4, 3, 2}

TreeForm[words]

enter image description here

This tree/expression/list has 3 levels. Levels provide a general way of specifying collections of parts in Wolfram Language expressions. Since it has 3 levels, you can use a maximum of 3 indices to extract parts of this list using the Part function. The following will get a word from the last level:

words[[3,2,2]]

But attempting to get words[[3,2,2,1]] gives the error "Part::partd: Part specification <<1>> is longer than depth of object."

At Level 0 we have the entire expression. At Level[expr,{-1}] we have a list of all "atomic" objects in the expression, in this case each individual word.

Your interpretation "level spec is the depth of these indices" therefore makes sense.

"levelspec" allows you to specify at which level a particular function should work on an expression. If we want to StringJoin the elements of words at level 2, we should Apply at level {2}.

In[40]:= Apply[StringJoin, words, {2}]

Out[40]= {{"anisotropymugful", "organistsocialization", 
  "worseningfeeder"}, {"mawkishnesspolity", "techniquecathartic", 
  "sorezenith"}, {"anilinelinguine", "brutalityboutonniere", 
  "noninterventionvenation"}, {"zirconiumcompartmentalization", 
  "pentathlonservitor", "immovabilityblah"}}

If we want to StringJoin at level 2, we need to Apply at level {2}:

In[41]:= Apply[StringJoin, words, {1}]

Out[41]= {"anisotropymugfulorganistsocializationworseningfeeder",  "mawkishnesspolitytechniquecatharticsorezenith", "anilinelinguinebrutalityboutonnierenoninterventionvenation", "zirconiumcompartmentalizationpentathlonservitorimmovabilityblah"}

Hope this helps.

Posted 3 years ago

This is a very low priority post concerning the behavior of Element and of SubsetQ.

First, there have been times when I wanted a function that checks that each element in a list is a real number. In the past I've resorted to variations of

realVectorQ1[vec_?VectorQ]:=Apply[And, Map[Chop[Im[#]]==0. &, vec]]

which can be improved, perhaps, using Element:

realVectorQ2[vec_?VectorQ] := Apply[And, Map[Element[#, Reals] &, vec]]

However, I just learned of the alternate usage for Element which allows it to apply to a list of alternatives, which means we could write the function as:

realVectorQ3[vec_?VectorQ]:=Element[Alternatives@@vec, Reals]

This is nice and short, but I find it confusing: why is Alternatives, which I think of as related to the logical operator Or, involved in an operation that seems to involve an And statement? Probably I'm just worrying too much.

My second question: why does SubsetQ not apply to domains as well as lists? It would be really nice to just use SubsetQ[vec, Reals], but both arguments need to be lists as far as I can tell.

Again, really low priority here. Ron

POSTED BY: Rongoetz

Thanks!!!!

POSTED BY: Angel Mosquera

Hi Ron, The use of alternatives in Element seems like a very function specific implementation where

Element[x1 | x2 | ... | xn, domain]

asserts that all the xi are elements of dom, i.e. for a domain dom, enter image description here

In fact you will see the following

In[4]:= Element[{x1, x2, x3, x4}, Reals]

evaluates to:

Out[4]= (x1 | x2 | x3 | x4) \[Element] Reals

Which is the same as

In[4]:= Element[#, Reals] &[{x1, x2, x3, x4}]

Out[4]= (x1 | x2 | x3 | x4) \[Element] Reals

You are right about SubsetQ -- it has been implemented to work for two lists, similar to other functions for operations on sets. (In the Wolfram Language, sets are represented by sorted lists.)

I got Switch to work with StringCases rather than StringMatchQ:

f[myInput_] :=
 Switch[
  First@StringCases[myInput, 
    "State" ~~ Whitespace ~~ s_ ~~ ___ :> s],
  "A",
  Print["action for A"],
  "B",
  Print["action for B"],
  _,
  Print["None of the above"]
  ]

This is doing a very simple pattern test. You'll need to work on the string pattern a little more to make it more robust. The way I arrived at the solution is by going to the documentation for Switch, and then after looking at the examples (neither of which had string matching examples) I wandered over to the linked tutorial (from the links at the top right). The tutorial on Conditionals demonstrated using If, Which and Switch. The example

r[x_] := Switch[Mod[x, 3], 0, a, 1, b, 2, c]

seemed closest to my need. Although, still not an example with Strings, I concluded if I could place my string pattern test as the first argument and pull out the matching part of the string, then each possible match (and the default _ ) could be one of my alternative "forms" of my switch statement, based on which I could return different outputs.

Hope this helps.

Posted 3 years ago

Abrita,

Thanks for the reply. I understand how Element is working, but not why. My question simplifies to: How am I supposed to understand that the syntax (x1 | x2 | x3 | x4) \[Element] Reals means the same as (x1 \[Element] Reals) \[And] (x2 \[Element] Reals) \[And] (x3 \[Element] Reals) \[And] (x4 \[Element] Reals)? Is that something I should be able to work out if I really understood Alternatives? Are there other areas where Alternatives is used like this?

My question about SubsetQ and related functions: I know they are intended for lists, I just think that it might be time for them to be extended to the more complicated classes of sets that have been implemented in the Wolfram Language lately (Region as well as the various domains). I'm guessing that's not an easy thing to do, but I can dream, right?

Thanks, Ron

POSTED BY: Updating Name

Hi Ron, Sure, I see where you are coming from. This really is a very specific use-case for Alternatives and if you are used to setting up Alternatives (as logical OR) for things like pattern-matching, the way it is used in Element can appear non-intuitive.

About your suggestion for extending SubsetQ to regions and domains, we'll be happy to forward it to the development team.

Posted 3 years ago
Import["hoffmann_ohno.mp4", "FrameCount"]

626

vid = Video["hoffmann_ohno.mp4"]; vidFrames = VideoExtractFrames[vid, All];

Length[vidFrames]

627

Are there 626 frames or 627 frames?

POSTED BY: Ulf Schmidt

Thank-you Abrita. Explained very well. John

POSTED BY: John Burgers

Try as I may the statement below to combine a video and audio into a video file didn't work for me. I gave up looking for help under Export to dissect the use of "Animation" , "Audio" ...

Export["sineManipulate3.mp4", {"Animation" -> 
   Manipulate[
    Plot[Sin[k x], {x, 0, 2 \[Pi]}, 
     PlotRange -> {-1, 1}], {{k, .1, "Wavenumber"}, .1, 5}], 
  "Audio" -> sufjanSong}, "Rules"]

Also got this error message which I couldn't understand or work with, Export::interr2: An unknown internal error occurred. Consult Internal`$LastInternalFailure for potential information.

Thanks in advance for any insight on where to look for assistance, John

POSTED BY: John Burgers
Posted 3 years ago

Hello, I created an app with 3 sliders, and I'm trying to position all three vertically and next to each other. Right now I only know how to place them vertically, with the 2nd and 3rd underneath the previous one. Thank you in advance for your help.

Corina

POSTED BY: Corina Murg

Hey John,

Forgive me if this is a silly question, but have you imported some audio to be saved as "sufjanSong"? Unfortunately it's a copyrighted audio track, so I couldn't include it with the files, and you would have to add your own audio track in order for this Export to work properly.

If you don't feel like downloading/importing your own audio track, you could always use one of our ExampleData files:

Export["sineManipulate2.mp4", {"Animation" -> 
   Manipulate[
    Plot[Sin[k x], {x, 0, 2 \[Pi]}, 
     PlotRange -> {-1, 1}], {{k, .1, "Wavenumber"}, .1, 5}], 
  "Audio" -> Audio["ExampleData/car.mp3"]}, "Rules"]

Video functionality is still fairly nascent in the Wolfram Language, and as a result you might not find it as well-exposed in the documentation as some of our more longstanding functionality. I found this Export functionality documented in this guide . Lastly, I'm not sure about the specifics of your error message there, but let me know if it persists after trying the above suggestion.

Arben

POSTED BY: Arben Kalziqi

Hi Hee-Young,

  1. This should explain the process of installing a stylesheet: https://reference.wolfram.com/language/howto/InstallAStylesheet.html. The installed stylesheet will appear in the menu beyond a divider separating it from the built-in stylesheets. The built-in stylesheets are present in the location but I would advise against editing the directory structure or files here:

    SystemOpen[FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd", "StyleSheets"}]]
    
  2. To change the layout of your table you could try using the ItemSize option to control the width of columns http://reference.wolfram.com/language/ref/ItemSize.html.

  3. To change to a PrintOut environment you can select from the menu Forrmat -> Screen Environment -> Printout enter image description here

Hope this helps.

You could use Grid or Column as shown in this example at http://reference.wolfram.com/language/ref/Slider.html

Playing a bit with the rules I found that:

{one, two, three, four} /. {x_, y___, z_} -> {y^z}

result in {two^three^four}

I would expect {two^four, three^four}

However, I found out that y___ returns Sequence [two, three] by applying the rule

{one, two, three, four} /. {x_, y___, z_} -> y  

which in corectly calculated as {two^three^four}.

Which rule would give the expected {two^four, three^four} ?

By trying to substitue the "Head" Sequence by a List head with Apply I have a difficulty to find out which is the head of the Sequence expression so Head[Sequence[two, three]] returns three[Symbol]. I would expect a head Sequence. Any explanation is welcome.

Commenting further on the post of larawag NN how can arbitrary precision 10 be better and more accurate than MachinePrecision which is almost 16 (15.9546) ?

Posted 3 years ago

I hate to bring this up, but in Quiz 2, problem 6 begins with the ungrammatical phrase "Which pure function takes a two inputs..." Clearly something is wrong here: I could delete the word "a" and get one answer, but if I imagine that the the question has missing words then I can easily find two words that would change my answer. I'm going with the choice of deleting the word "a", but thought you might want to fix the question at some point.

POSTED BY: Rongoetz

The correct text of the question should be: "Which pure function takes two inputs and returns a list of their sum, difference and product?"

We're working on updating the quiz itself. Thank you for reporting the issue.

Posted 3 years ago

What is the email to query the exercises that are not marked correct by the auto grader? Can we just send the code for the specific question?

POSTED BY: Doug Beveridge

Call me crazy, I work with Mathematica on a 60 inch Samsung monitor. I'd like some guidance on how to reset Mathematica defaults (window size, text size ) when opening new sessions and work books. Could all the adjustments be made in the Option inspector? Currently I use Cntrl- mouse scroll to adjust the text inside the notebook to a reasonable size, which has not effect on the Window Title and tool bar. Thanks in advance for any help or pointing me to further reading.

Great job Arben and Abrita, the course surprised me in how much I picked up, and by it's breadth. Exciting ride keeping up with the pace. John

POSTED BY: John Burgers
Posted 3 years ago
POSTED BY: Michael Hobbs

I just want to point out that when you send your solution to the autograder (by clicking on the "Check Solution" button) it does not have access to any definitions you may have created in the exercise notebook itself. So you will have to include that definition as part of your solution.

myList = {1,2,3,4};
Part[myList,2]

or

myList = {1,2,3,4};
myList[[2]]
Posted 3 years ago

I think there could be an error in question 2.5 of the exercises

"starting from n=0 to n=4"

should be "starting from n=0 to n=5 "

Please give that email address so we can query solutions to the auto-grader.

POSTED BY: Doug Beveridge
Posted 3 years ago

Thank you Abrita, that has resolved the problem.

POSTED BY: Michael Hobbs

Good day, everyone!

I just don't understand how my solution is not right. I tried different implementations and re-checked many times. Please, assist me, what it wrong?

enter image description here

POSTED BY: Fedor Sumkin
Posted 3 years ago

I get the same result , I think the auto-grader is not picking up the right solutions

Similarly 12.2 solution correct but rejected .

12.3 solution correct but get an error "ToExpression::sntxi : Incomplete expression; more input is needed"

POSTED BY: Doug Beveridge

Hi Everyone, I'm not having luck with the autograder input box. I've read Abrita's note above that a complete statement, or compound statement, including any definitions, is needed. For example exercise 2.3 I got the same statement in a practice notebook were the statement==answer yields true, copied the statement to the grader box where it says "try again". I think it was Abrida who said in this cases to log on to the Wolfram account - my files - copied files folder and email you a download. Is that the procedure ? Can you remind me, or post, the email addresses we can send to? Thank you John.

POSTED BY: John Burgers

12.3. the same here. My solution works without ToExpression, so this message seems to be affected by the autoconverter.

If I wrap a ToExpression around [mysolutionthatcreatesthewantedoutput] in my Mathematica installation, he shows the resulting picture next to the error "Expression can only interpret strings or boxes as Wolfram Language input."

POSTED BY: Andreas Rudolph
Posted 3 years ago

No fun ! Not sure, who should try again ...

enter image description here

@Fedor Sumkin: your Complement approach is more elegant!

POSTED BY: Peter Lippolt

Have you checked that your solution does not include unwanted "blanks"? I typically work with my local Mathematica, and copy paste finished solutions over into the examination notebook. For some solutions he shows me a "try again". If I remove all excess blanks directly in the examination notebook it sometimes works. Your "vowel" string appears to be a bit suspicious. (just an idea)

POSTED BY: Andreas Rudolph
Posted 3 years ago

Andries Do you get a solution to work with Ex 2.3 . What operating system are you using. I am using Windows 10.

I have followed your advice and removed all blanks and created my vowels and consonants using Alphabet[] but still no joy.

POSTED BY: Doug Beveridge

In 2.13. I have the correct result with some sytax error that I do not understand what it means. My answer cannot be evaluated as correct.

In 2.17 also the correct answer cannot be evaluated as correct.

enter image description here

Hi Doug, We would like to request you to download the entire exercise notebook with your final solutions and email it to wolfram-u@wolfram.com

Hi Doug,

Remember

NestGraph[f,expr,n]

gives the graph obtained by starting with expr and applying f successively n times. So if you want the final output to be the result of applying f on the values say 0,1, and 2 you will need to nest it 3 times.

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