Message Boards Message Boards

GROUPS:

[WSG21] Daily Study Group: Wolfram Language Basics

Posted 6 months ago
6919 Views
|
122 Replies
|
37 Total Likes
|

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!

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

Posted 5 months ago

Happy to be a part of this study session cohort!

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.

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 5 months 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 5 months 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 5 months ago

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

Posted 5 months 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

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

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 5 months 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

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

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

Posted 5 months ago

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

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.

Posted 5 months ago

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

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

Posted 5 months 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 5 months 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

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 5 months ago

Thanks Abrita for the explanation!

Posted 5 months 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?

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 5 months 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).

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 5 months ago

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

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

Arben

Posted 5 months ago

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

Posted 5 months 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] ?

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.

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 5 months ago

When will the Advanced Programming recording become available to rewatch?

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

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

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?

Posted 5 months ago

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 5 months 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.

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"
Posted 5 months ago

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

Attachments:

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 5 months ago

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

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.

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

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.

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

Thanks!!!!

Posted 5 months ago

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

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 5 months ago

Thank-you Abrita. Explained very well. John

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?

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 5 months 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"]]

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 5 months 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} *)

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 5 months 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 5 months 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 5 months ago

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

someText = {"State A", "State A1", "State A2", "State B1", "Random Test"};
Posted 5 months 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 5 months ago

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

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.

Posted 5 months 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

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.)

Posted 5 months 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

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 5 months 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 5 months ago

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

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 5 months ago

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.

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.

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.

Posted 5 months 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

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.

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
Posted 5 months 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:

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 5 months 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.

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 5 months 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?

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

Posted 5 months ago

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

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 5 months ago

Hi, and thank you for all you excellent teaching.

I've just written three answers (all of which gave the expected outcome), for 2.1 in the level 1 exercises. All were rejected by the check answers button.

Thanks for any help you may give. Michael

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 5 months ago

Thank you Abrita, that has resolved the problem.

Posted 5 months 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.

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.

Posted 5 months ago

I used an expression in the form of

NestGraph[f , 0 , 5]

and produced the graph and was accepted by the autograder .

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 5 months 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 5 months ago

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 5 months ago

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 5 months 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.

Hi Fedor, Please feel free to send your exercise notebook with all the solutions to wolfram-u@wolfram.com. Your solution looks fine.

Posted 4 months ago

Dear Abrita,

Since I experience the same validation problem commented on in the thread. Can you give me instructions on how to download the "WSG: Wolfram Language Basics | Level I Certification" notebook to be conveniently fulfilled and emailed to wolfram-u@wolfram.com? I only see a web page without download options how I could see in Wolfram|One.

Best regards Gustavo

Posted 5 months ago

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 5 months ago

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

enter image description here

@Fedor Sumkin: your Complement approach is more elegant!

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

Posted 5 months ago

Are there more statements involved when you developed the answer, which perhaps are required to also be copied to the answer field?

Hi Everyone, I understand you have been running into some issues with the autograder. If your solution is generating the same output as shown in the expected output and you are satisfied with all your code, please download a copy of the exercise notebook and email it to us wolfram-u@wolfram.com.

You will find the exercise notebook in the "Copied Files" directory among your cloud files. It should appear as "02_exercise.nb"

enter image description here

Good day, everyone.

Being a russian, I'd like to point out, that we have 10 vowels in our alphabet: а, я, о, ё, ы, и, э, е, у, ю. I can solve exercise 2.11 of the exam the way you want me to, but that'd be wrong.

Hi Fedor,

Thank you for your feedback. We have made note of the issue. For this specific exercise, we will rephrase the question as follows:

Make a list of the letters in the Russian Alphabet, with the five letters {а,е,и,о,у} in Style Red. (Hint: Use ReplaceAll and string pattern matching with StringMatchQ. Restrict the match to be a String before trying to match it against the letters {а,е,и,о,у}.)

Facing hurdle adding images to the notebook. Here is the original thread that I posted: https://community.wolfram.com/groups/-/m/t/2211885?ppauth=P83yUOh1

Hi Rajeev,

For the purposes of this particular study group I would encourage you to use Wolfram|One and the regular Wolfram notebook which offers some more flexibility in adding different types of content (text, code or images) to the notebook. You will have more freedom to write your own code in the Wolfram Language in this notebook. And to add images you can simply copy and paste them into your notebook.

The Wolfram Alpha Notebook Edition is intended for slightly different use--to enable users to provide free-form input to get instant answers to questions, create and customize graphs, and also add their own notes in text.

Please let us know or feel free to contact our support team if you have further questions about which product will best suit your needs and expectations. Thanks

Tried Wolfram Notebook (https://develop.wolframcloud.com/env/286fe86b-1d85-4150-8150-abfd773e80d7) by drag & drop, CtrlC + CtrlV, and copy/paste options. No way I could insert image. No option to upload image from desktop despite this message after clicking enter image description hereInsert Image:

Insert Image Drag and drop an image from the desktop into your notebook, or use Import to import an image from file.

Posted 5 months ago

Hi Abrita

for 2.17 I have a solution using (as requested) "MoleculeRecognize" that just works fine in my local installation.

When I enter this solution into the exercise notebook, the Wolfram Cloud replies with below message. In-place evaluation and as well the autograder fails. Probably it is not possible to pass the exams without sending you the finished notebook by mail (at the end).

Just to let you know

br Andreas

enter image description here

Posted 5 months ago

My local installation of 2.17 works with my solution also without errors. However, in the cloud I get a completely different error message than Andreas. (@Andreas I put the entries in ChemicalData["name","property"] in different order, please see the reference.)

Maybe "my error message" is because I pasted the image directly into my solution? - But: How else?

Attachment

Attachments:
Posted 5 months ago

Hi larawag NN

as by instructions "Use "MoleculeRecognize" to identify the molecule in the following image....".

In my first line, I write " molec = MoleculeRecognize [paste here the given picture]".

If I paste just this first line into the "exercise notebook" (observe in the first lines that these seem to be local copies) and run it, he replies with "MoleculeRecognize" is not currently supported in the Wolfram Cloud". The rest of the messages from "ChemicalData" etc are just follow-on problems, as "molec" already fails.

BR, Andreasenter image description here

Hi Andreas and Larawag,

I have noticed the issues with both the questions using images. I have come to a similar conclusion as you both. Although your image processing code runs just fine on your local installations, the autograder seems to be running into an issue with the same code snippet in a cloud sandbox. We are looking into it. Hopefully we'll have a resolution soon. And as you have quoted, we do have the backup option of emailing the notebook. Thanks everyone for your patience as we work through these issues.

Best, Abrita

Good day, everyone.

I completed the exams notebook (not all of it, if we are to believe the results of the "Check" button). Earlier I was advised to submit the notebook via email. However, when I try to, I get the "Client host rejected: Your message was rejected due to spam filtering. Please see http://www.sophos.com/security/ip-lookup..." mail send error.

So, the questions I'd like you to assist me with are the following. Are there any other ways to submit the notebook? How do I know, if and when all the results (quizes and exams) are recieved and are ok (or not)? What does humanity exist for? The last question is optional.

Hi Fedor,

  1. The email address wolfram-u@wolfram.com is able to receive emails with attachments from all our users. We have not run into this issue before. We'll check again and keep you posted.
  2. Folks have until March 19 to complete the quizzes and exercises. We'll tally up the scores after that and send you notification via email.
  3. To continue the never-ending quest for knowledge? :)

This is an automatically generated Delivery Status Notification.

Delivery to the following recipients failed permanently:

  • "wolfram-u@wolfram.com wolfram-u"@wolfram.com

Reason: Permanent Error

I was having trouble with auto grader on 7 problems. I was trying to submit a nb file with the solutions.

My delivery issue appears to be an issue with the email address string from a copy paste. It appears resolved.

I have a similar problem starting with first question. I used a shorthand notation of Part without "Part" that produced the requested elements from the question, but was marked wrong by auto-grader.

I'll keep working on the exercises.

Hello,

I'm just re-reading and executing the notebook codes. Again, what an abundance of inspiring examples! Thanks :-)

Arpad

Posted 4 months ago

Hello,

I got my level 1 certificate today. Thank you very much for that. I still do not know what the problem was with the 6 results which have been marked as wrong, although my final result matched the expected result in 100%. Do I have to discard the way I used to solve them in the future, since I was on a completely wrong way, or was it just a glitch in the autograder?

It would be great if we could get a final notebook with the official right results so that we can see how we did in the exam, and where we could get better.

Best regards, Dr. Peter Lippolt, Hannover, Germany

Dear Dr. Lippolt,

All your solutions were accepted during manual grading of the exercises. We faced some issues with the auto-grader accepting alternate solutions to some of the problems. Our apologies for the inconvenience.

Posted 4 months ago

Dear Abrita Chakravarty,

thank you very much for your fast reply. Now I know that my solutions were on the right way.

The complete study group was really well organized, and I have again seen a lot of new ways into the Wolfram language. The quizzes are a perfect way to make sure that the content is understood, and solving them gives much better insights in practical usage than just consuming a presentation. Always a pleasure to follow your events in Wolfram-U. Looking forward to other events to come ...

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