NumPy (2/2)
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 43 | |
Author | ||
Contributors | ||
License | CC Attribution 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor. | |
Identifiers | 10.5446/38198 (DOI) | |
Publisher | ||
Release Date | ||
Language | ||
Production Place | Erlangen, Germany |
Content Metadata
Subject Area | |
Genre |
4
5
6
7
9
10
11
14
28
29
32
33
34
35
38
39
41
43
00:00
Matrix (mathematics)IntegerGrand Unified TheoryUser interfaceRadio-frequency identificationParameter (computer programming)DiagonalElement (mathematics)InformationSystem calloutputAttribute grammarModule (mathematics)MereologySlide ruleAreaMultiplication signSemiconductor memorySeries (mathematics)Operator (mathematics)Spherical capCASE <Informatik>Theory of relativityRule of inferenceState of matterBit rateVideo gameDependent and independent variables1 (number)Arithmetic meanClosed setOffice suiteNominal numberTouch typingEqualiser (mathematics)Goodness of fitBasis <Mathematik>Reading (process)Perfect groupProcess (computing)Matrix (mathematics)Element (mathematics)FreewarePiShape (magazine)Parameter (computer programming)Object (grammar)Electronic mailing listIntegerArray data structureComputer animation
05:50
Parameter (computer programming)Radio-frequency identificationDiagonalElement (mathematics)Uniform resource nameIntegerUser interfaceInformationMatrix (mathematics)Default (computer science)Function (mathematics)Price indexRandom numberNegative numberLaptopType theory10 (number)Functional (mathematics)Task (computing)DiagonalWebsiteOrder (biology)Different (Kate Ryan album)Endliche ModelltheorieCondensationBitMatrix (mathematics)NumberRange (statistics)1 (number)Element (mathematics)Default (computer science)Parameter (computer programming)ProgrammschleifeDiagonal matrixOnline helpPoint (geometry)Arithmetic meanResultantExecution unitWeb pageBit rateMedical imagingException handlingProcedural programmingTouch typingOpen setComputer configurationMachine visionRule of inferenceSound effectLogicComputer fileLattice (order)Right angleComputer animation
13:40
DiagonalPrice indexInformationParameter (computer programming)Function (mathematics)Default (computer science)Negative numberInterior (topology)Random numberUser interfaceArray data structureKernel (computing)Grand Unified TheoryLaptopGraph coloringMatrix (mathematics)Shape (magazine)Element (mathematics)Interior (topology)Default (computer science)Kernel (computing)Square numberLibrary (computing)Random number generationData structureRepresentation (politics)CodeNumberDifferent (Kate Ryan album)Parameter (computer programming)Function (mathematics)DiagonalMultiplication signData typeRoundness (object)Functional (mathematics)Poisson-KlammerShift operatorRow (database)Identity managementVideo gameRight angleMachine visionAdditionData recoveryHypothesisGoodness of fitVotingVibrationMereologyHypermediaMusical ensembleComputer animation
21:31
Random numberSubject indexingArray data structureElectronic mailing listMatrix (mathematics)Medical imagingHistogramRandom number generationData structureRandomizationCASE <Informatik>Program slicingBitDistribution (mathematics)Casting (performing arts)Cartesian coordinate systemNumberMultiplication signDifferent (Kate Ryan album)Computer animation
23:49
Array data structureSubject indexingPrice indexElement (mathematics)Negative numberCountingHausdorff dimensionPresentation of a groupUser interfaceLine (geometry)Electronic mailing listGame controllerOperator (mathematics)Inheritance (object-oriented programming)EvoluteOffice suiteElement (mathematics)Array data structurePrice indexSubject indexingView (database)Game theoryDimensional analysisBitForm (programming)Program slicingException handlingComputer animation
26:58
Subject indexingArray data structurePrice indexElement (mathematics)CountingNegative numberHausdorff dimensionElectronic mailing listMatrix (mathematics)Dimensional analysisPoint (geometry)InformationSpacetimeProgram slicingElement (mathematics)Cartesian coordinate systemImpulse responseCASE <Informatik>Direction (geometry)Event horizonNumberBitPresentation of a groupRange (statistics)RAIDMultiplication signComputer animation
28:44
Hausdorff dimensionMassBoolean algebraSubject indexingUser interfaceElectronic mailing listProgram slicingGame theoryNumberRow (database)Element (mathematics)Multiplication signComputer configurationArithmetic meanComputer animation
30:04
Hausdorff dimensionMassBoolean algebraSubject indexingElectronic mailing listGoodness of fitBitClosed setComputer animation
31:48
Hausdorff dimensionFigurate numberRow (database)NumberProgram slicingSubject indexing3 (number)WritingDifferent (Kate Ryan album)Computer animation
33:13
Hausdorff dimensionLattice (order)System callPlanningGoodness of fitService (economics)AuthorizationCASE <Informatik>Row (database)NumberSlide ruleShape (magazine)Direction (geometry)Array data structureVector spaceGradient descentComputer animation
36:03
MassBoolean algebraSubject indexingLinear regressionGame theoryEuler anglesBitTouch typingCASE <Informatik>Computer configurationRight angleProgram slicingPoint cloudElement (mathematics)Condition numberGoodness of fit7 (number)AreaPosition operatorAuditory maskingComputer animation
37:19
Hausdorff dimensionMassBoolean algebraSubject indexingForm (programming)Matrix (mathematics)Poisson-KlammerElement (mathematics)Boolean algebraOperator (mathematics)Computer configurationVideo gameLine (geometry)WritingComputer animation
38:37
IntegerSubject indexingMassBoolean algebraCartesian coordinate systemPrime idealElement (mathematics)Interior (topology)Grand Unified TheoryHausdorff dimensionSystem callScalar fieldAnalog-to-digital converterArray data structureElement (mathematics)Row (database)Matrix (mathematics)Product (business)CASE <Informatik>1 (number)Subject indexingGoodness of fitShape (magazine)Metropolitan area networkMilitary baseEntropie <Informationstheorie>Insertion lossDifferent (Kate Ryan album)CausalityMultiplication signBitComputer configurationNumberForm (programming)Video gameRegular graphCasting (performing arts)Auditory maskingBoolean algebraPosition operatorCondition numberCartesian coordinate systemComputer animation
42:33
Interior (topology)Subject indexingMassBoolean algebraSystem callScalar fieldAnalog-to-digital converterArray data structureRandom numberoutputTable (information)Type theorySoftware testingInformationFile formatIntegerCoroutinePrice indexPoint (geometry)Parameter (computer programming)Inheritance (object-oriented programming)Limit (category theory)Internet forumElectronic design automationOperations researchHausdorff dimensionMilitary operationShape (magazine)Metropolitan area networkEuler anglesStack (abstract data type)Expandierender GraphRead-only memoryElement (mathematics)Block (periodic table)Duplex (telecommunications)Source codeOrder (biology)AngleAuditory maskingSound effectSource codeXMLComputer animation
43:52
Duality (mathematics)Interior (topology)Boolean algebraMassSubject indexingArray data structureAnalog-to-digital converterSystem callScalar fieldCartesian coordinate systemElement (mathematics)IntegerExecution unitFlow separationImpulse responseTerm (mathematics)AreaElectronic mailing listSelectivity (electronic)Auditory maskingData conversionElement (mathematics)Prime numberSource codeXMLComputer animation
45:40
Cartesian coordinate systemElement (mathematics)Interior (topology)Condition numberLimit (category theory)Rule of inferenceVideo gameFamily2 (number)Computer configurationMultiplication signNumberElement (mathematics)Disk read-and-write headBit rateCellular automatonMixed realityElectronic mailing listArithmetic meanCASE <Informatik>Square numberDivision (mathematics)Prime numberMaxima and minimaIntegerComputer animation
48:28
Cartesian coordinate systemElement (mathematics)IntegerPrime idealInterior (topology)Prime numberNumberRootSquare numberType theorySubject indexingCartesian coordinate systemPrime idealBitElement (mathematics)MereologyLine (geometry)2 (number)Program slicingVector potentialBoolean algebraMusical ensembleCASE <Informatik>Sampling (statistics)Sign (mathematics)TrailComputer configurationExclusive orHand fanHypermediaData storage deviceMultiplication signOffice suiteBit rateCausality40 (number)DemosceneDifferent (Kate Ryan album)Compass (drafting)Computer animation
52:43
Element (mathematics)Cartesian coordinate systemInterior (topology)Prime idealSummierbarkeitUser interfaceHacker (term)System identificationHausdorff dimensionMixed realityCartesian coordinate systemElement (mathematics)Subject indexingSummierbarkeitDimensional analysisPositional notationPlanningMatrix (mathematics)Price indexTerm (mathematics)Row (database)Associative propertyDifferent (Kate Ryan album)Series (mathematics)Bit rateRule of inferenceCASE <Informatik>Military baseGame theoryDigital photographyGroup actionLogic gateBasis <Mathematik>ArmPentagonComputer animation
57:52
Array data structureHausdorff dimensionPlanningMedical imagingCartesian coordinate systemLevel (video gaming)Subject indexingRow (database)Element (mathematics)Interior (topology)MereologyMatrix (mathematics)Poisson-KlammerBitStatement (computer science)SpacetimeElectronic visual displayOffice suiteParameter (computer programming)Form (programming)Computer animation
59:35
SummierbarkeitCartesian coordinate systemHausdorff dimensionDrum memoryArray data structureMedical imagingCartesian coordinate systemFilm editingRange (statistics)Form (programming)Term (mathematics)Bit ratePosition operatorDifferent (Kate Ryan album)Quantum statePlanningDirection (geometry)CASE <Informatik>WebsiteAreaMusical ensembleMachine visionComputer animation
01:02:08
Cartesian coordinate systemPrice indexHausdorff dimensionArray data structurePlanningDirection (geometry)Cartesian coordinate systemElement (mathematics)Rule of inferenceData storage deviceSubject indexingComputer animation
01:03:27
Array data structureHausdorff dimensionCartesian coordinate systemPrice indexOperations researchMilitary operationSinePlot (narrative)Random numberMatrix (mathematics)User interfaceLaptopRoutingDot productArray data structureBinary multiplierLinear algebraMultiplicationMultiplication signElement (mathematics)Price indexPlanningMereologyMatrix (mathematics)Film editingNeuroinformatikVector spaceComputer programmingCartesian coordinate systemExpected valueSubject indexing2 (number)BitOperator (mathematics)NumberMachine visionDisk read-and-write headThermal radiationFingerprintSound effectGroup actionComputer configurationGame theoryMountain passDecision theoryGreatest elementInheritance (object-oriented programming)Reading (process)Metropolitan area networkScaling (geometry)Office suiteCausalityMedical imagingComputer clusterHamiltonian (quantum mechanics)Text editorWordExecution unitComputer animation
01:10:51
Dot productMatrix (mathematics)Matrix (mathematics)QuantificationQuicksortMultiplication signMultiplicationBlock (periodic table)Operator (mathematics)Decision theoryReading (process)Different (Kate Ryan album)Execution unitGroup actionContent (media)Computer animation
01:12:06
Matrix (mathematics)Military operationOperations researchDot productUser interfacePlot (narrative)Random numberSineBlogProduct (business)Computer configurationOffice suiteMultiplication signTouch typingDirection (geometry)Uniformer RaumFingerprintRow (database)Right angleResonatorGroup actionNeighbourhood (graph theory)Annihilator (ring theory)ResultantSpecial unitary groupSheaf (mathematics)Digital electronicsSingle-precision floating-point formatBit rateGraph coloringSeries (mathematics)Random walkSummierbarkeitCodeCASE <Informatik>AngleTrigonometric functionsFunctional (mathematics)LengthPoint (geometry)MathematicsView (database)Range (statistics)RootMatrix (mathematics)Square numberVector spaceMultiplicationComputer animation
01:17:46
Random numberSinePlot (narrative)Line (geometry)MathematicsBroadcasting (networking)Range (statistics)OvalProgrammschleifeUser interfaceGroup actionTouch typingRule of inferencePiSpecial functionsIntegerRange (statistics)Broadcasting (networking)NumberArray data structurePoint (geometry)CodeLaptopElement (mathematics)BitModule (mathematics)Object (grammar)MathematicsFunctional (mathematics)RootElectronic mailing listSquare numberAddress spaceCASE <Informatik>DivisorDistanceArithmetic meanMultiplication signHypothesisFigurate numberComplex (psychology)Computer programmingDifferent (Kate Ryan album)CoprocessorNeuroinformatikReal numberGoodness of fitWebsiteVideoconferencingComputer cluster2 (number)Bit rateCodecScaling (geometry)Machine visionOperator (mathematics)Sign (mathematics)Basis <Mathematik>Hybrid computerExecution unitComputer configurationComputer animationLecture/Conference
01:22:46
AngleConvolutionSineMaxima and minimaCoroutinePoint (geometry)Cellular automatonInverse hyperbolic functionProduct (business)SummierbarkeitPotenz <Mathematik>Parameter (computer programming)Internet service providerSeries (mathematics)Asynchronous Transfer ModeShape (magazine)Broadcasting (networking)Array data structureHausdorff dimensionFunction (mathematics)Array data structureOperator (mathematics)Line (geometry)Electronic mailing listDifferent (Kate Ryan album)Combinational logicInformation securityCondition numberPosition operatorFunctional (mathematics)Figurate numberComputer animation
01:24:02
Shape (magazine)Broadcasting (networking)Array data structurePoint (geometry)Hausdorff dimensionLengthDimensional analysisNumberKey (cryptography)Rule of inferenceSet (mathematics)Shape (magazine)Integrated development environmentMedical imagingArray data structureElectronic mailing listBitBroadcasting (networking)Operator (mathematics)Matrix (mathematics)PlanningQuantum stateRight angleWritingComputer animation
01:25:31
Shape (magazine)Broadcasting (networking)Shape (magazine)Database transactionProduct (business)Game controllerShared memoryOffice suiteBroadcasting (networking)Matching (graph theory)Correspondence (mathematics)Cellular automaton1 (number)Direction (geometry)Fitness functionDimensional analysisComputer animation
01:26:50
Shape (magazine)Broadcasting (networking)Array data structurePoint (geometry)Hausdorff dimensionQuantum stateDimensional analysisLengthNumberShape (magazine)Universe (mathematics)Natural numberMultiplication signState of matterMilitary baseMedical imaging1 (number)Fitness functionPoint (geometry)Computer animation
01:28:24
Mandelbrot setPoint (geometry)Array data structureBoolean algebraApproximationRandom numberSeries (mathematics)Limit (category theory)AlgebraLinear mapEigenvalues and eigenvectorsInterior (topology)Product (business)Matrix (mathematics)Cholesky-VerfahrenNormed vector spaceCondition numberNichtlineares GleichungssystemOrder (biology)AverageMedianHistogramFunction (mathematics)Plot (narrative)Partition (number theory)Computer-generated imageryCartesian coordinate systemMandelbrot setRepository (publishing)MereologyCombinational logicGoodness of fitEigenvalues and eigenvectorsCalculationLinearizationVector spaceProduct (business)Group actionStatisticsSpeech synthesisTheory of relativityBit rateMedical imagingAuditory maskingLogical constantArray data structureLaptopComputer animation
01:30:21
Table (information)Array data structureBroadcasting (networking)Random numberSign (mathematics)Buffer overflowFC AugsburgSelf-organizationLaptopDemo (music)Computer multitaskingComputer-generated imageryPresentation of a groupComputer programmingGame controllerPresentation of a groupProbability density functionRevision controlLaptopRepository (publishing)Computer animation
01:31:51
Computer animation
Transcript: English(auto-generated)
00:05
Hey, now we come back to the second part of the tutorial of the new slide. In the first part, we have discussed this important concept of use. And I just want to give you a brief example of how crazy things can be with use by manipulating strides.
00:26
I mean, this is not meant as part of the material which I want to teach you, but just to give you an idea of what one can do. Let me just produce a matrix which is my innocent living, a 2x2 matrix, 16 elements.
00:43
And now if I choose the strides to be 16, 16. Try to figure out what to get then. Get this matrix. How do we get it?
01:00
Well, 16 means, since the item size is 8 here, 16 means you're going steps of two elements. And no matter whether you're going horizontally or vertically, you're always going steps of two objects. That means if I go this way, I just take every second object, a repeat process.
01:22
If I go in this direction, I also take every second object. So these are the same data, but just a different tool. And of course, if I have something different, because you have a different size, then you have to divide by two.
01:47
But I could also go in steps of four bytes, and I get something crazy. Because I'm jumping in the middle of an integer. And Biden just integrates what's there.
02:01
So what I want to say here is, if you do tricks like this, and this is just parts of those pie tricks, then you're responsible for whatever happens, and bad things will happen. OK, but that was just to get you back into discussion here.
02:21
Let's try to create some matrices. I wanted to ask about the sprites. Does that also work with free bytes? In principle, yes. Any integer bytes is a relevant step size.
02:45
So divide the applications for that. There you really should know what you're doing.
03:03
So far, our usual way to create arrays was really by writing down lists of lists and converting them into an array. That's often not what you do. And quite often, actually, the first step to create an array is to create an array of zeros.
03:28
So what you can do is you can just say, I'm going to have an array filled with zeros of a certain shape. So the first argument is shape. Here, I'm saying I want a 4 by 4 matrix filled with zeros.
03:44
Actually, you can also ask for an empty array, but watch out. An empty array doesn't mean that it's filled with zeros. That's why that is the method zeros. An empty array just takes some chunk of memory and takes whatever is there.
04:03
So it's your responsibility to make sure that all elements are filled again. Whereas often, one has an array where only some matrix elements need to be filled, while other matrix elements should be zero. And then the best thing is to start from zeros.
04:25
And then, of course, we get an array filled with zeros. Now, a question for you. How do I get an array filled with ones? Oh, but you're supposed to do the 4 by 4 array.
04:45
Once you get your views, you can discount it right away. And of course, if you want to do something more complicated,
05:01
you can say the 4 by 4 will be discovered. You can do that, of course. Now, how do you get an array filled with tens? There's tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens, tens?
05:31
This is not the right way to do it. So how can we get this multiply the area of the array? I mean, we can do computations with ones.
05:45
This is actually not as innocent as it looks like. You might say, of course, if I multiply a lot of ones with tens, I get a lot of tens. There is some logic behind it, which I need to explain to you as we go on.
06:03
How can I force it to be an integral? You could, we have said that the default type is flow. So I could say the p-type should be hint. Then it's integral. So you can define the type. So in particular, for the next interesting, also for the zeros,
06:24
if you define the p-type of Boolean, then zeros will be false.
06:41
So that's a way to initialize a Boolean array. In principle we can multiply an array in this way, but there's more to tell you about that. I'll come back to this point later.
07:01
Now, what you often have is diagonal matrices. So suppose I want to have a 4 by 4 matrix with 1, 2, 3, 4 on the diagonal. Just say p-type. It's in the diagonal matrix.
07:20
Now, this function, this method, has an optional argument, a. So I would like to ask you to experiment with it. If you say, in addition, comma k equals 1 or minus 1,
07:40
just try out what happens then. So you see, the numbers are shifted from the diagonal.
08:01
At the same time, the array has become a bit larger to accommodate all the values. But in this way, you can fill off diagonal elements. Sometimes it's very useful. If you happen to work in condensed metal physics, and you know what a tie-binding model is,
08:21
I mean, the matrix called the hopping between different data sites can be immediately constructed in such a way. If you don't know what that is, what I'm talking about, don't worry. But I mean, it happens occasionally that you have matrices where you mostly have diagonal elements and some of them. It should be easily solved.
08:44
Extracting? Or you mean to load the diagonal? Only if you want. Then you have to flip the matrix around.
09:02
Oh, no. You can set it to minus 1. Then you'll go to load the diagonal. But I think that was not your question. If you write it, then you can do it this way. Then you have to flip the matrix. You will left-right flip it off the matrix and up, flipping, this is my question.
09:28
OK, this way. Just done. Now, if I do that on a 2D matrix, how do I get that? So the task for you is to find a 2-dimensional matrix.
09:44
Just for simplicity, a range of, let's say, 16, reshape it into a 2 by 2 or 4 by 4, 2-dimensional matrix, and try to operate NP-DIAG on this 2-dimensional matrix. What happens?
10:18
A range looks like this.
10:46
It's just a diagonal. So this works basically in two ways. If you start out with a one-dimensional array, it produces a diagonal matrix, or matrix with a shifted diagonal. If you do it the other way around, it tracks the diagonal.
11:10
And there's another function, NP.I, which is somehow related to find out what a function does if you know its name.
11:20
Just ask for help by NP info, for example. This results in a 2D array with 1's on the diagonal and 0's elsewhere. So that's basically a bit simplified. You don't have to create the 1D array in order to create this diagonal element.
11:43
The I function will do this for you. And now suppose I want to have a matrix which looks like this. And the task for you is to create this by means of the I function. Try this.
12:02
Might help to read the documentation briefly. Let's see how we manage to produce this matrix without typing in all the matrix elements explicitly. Imagine this should be a function by a thousand matrix.
12:20
Then you definitely don't want to type in all the matrix elements. And you don't want to write loops over the matrix elements to build a matrix. You want to do it as simple as possible.
13:33
So how do we do it? Well, the I function has the argument n. You see all other arguments have default values.
13:43
So n is really the important argument which you first have to take a look at. It tells you the number of rows in the output. So we have the 3 by 3 matrix, so n should be 3. Well, that is another argument which is n, the number of columns.
14:00
But you see this has a default value. So if this is none, if it has its default value, it defaults to n the number of rows. So this would be a square matrix. So there's no need to put in n. It's sufficient to specify n. k, as before, gives you a shift relative to the main diagonal.
14:22
And while we can make sure that the data type is correct, we can fix the data type, which by default is float. So this tells us that we could use MPI of 3, p-type, p-int.
14:45
Now, in the main diagonal, we want to have 2. So we have to multiply by 2. And then we add MPI of 3, k equals 1, int plus MPI of 3,
15:08
k equals minus 1, p-type, p-int.
15:31
Come on. Yeah, I know. This is this. Automatism in IPython that there are extra brackets.
15:44
OK, so you just add up three times i's, multiply them, and shift the i's. Can the good way to assign the same value to all elements in the array to create an i as 1, and then we divide by the number?
16:01
Yes. That's the easiest way to do it. I think that's very transparent, because in this way, you don't have to attribute the value to each element one way.
16:23
And MP1s, I mean, these functions are supposed to be very efficient, because their numpy really knows what to do and to do it in. OK, something that actually needs relatively often,
16:42
particularly if you're doing simulations, for example, is to create random numbers. And often in a simulation, what you might end up doing is to create one random number after the other, and you run your simulation. The advantage here in numpy is that you can create
17:03
a lot of random numbers in one round. So this is relatively efficient. And you can even define the shape. So I'll get here with random rand. It gives me numbers between 0 and 1 in the matrix of a given shape.
17:21
So this will be a 5 by 2 matrix of random numbers. Of course, each time I'm running this, I'll get different random numbers. So this is 0.415. I run it again. I'll get a different number.
17:42
Sometimes you want to have your code to be reproducible. So what you can do is you can define the initial C, and then you'll always get the same random numbers. So here I have started 191.
18:00
So I run this again. I get the same random numbers. I can do this in a reproducible way. And now occasionally, you have matrices. So if you kill the kernel, you have to set C. What would it do to say C? No, if you kill the kernel, then everything is locked away.
18:25
Yeah, sure. If you just execute the first library to reduce random numbers. This one here? Yeah. Then kill the kernel. Are they different from this set? They are different. So there's no initial C which is set all the time?
18:42
I mean, we can try this, but we just have to import a few new things again on that C. Even if you don't remember the random numbers,
19:36
I think you remember that there was no 0.64 on the top.
19:40
So don't have an initial C in the kernel. That would actually also be not a good way to put your assignment. I mean, it's really the C which defines the random numbers, which gives you well-defined random numbers. If you don't want that, you shouldn't get it arbitrarily
20:01
by just killing the kernel and finding something. It still makes sense. Initial C is correct. There's no initial C in this sense, no well-defined initial C. It makes sense because that's what you might want.
20:21
If you don't want it, you should fix the C yourself. Now, when you are using numpy arrays, you will find out that if you have 100 by 100 arrays, for example, then numpy will not be showing all the matrix elements anymore
20:40
because that doesn't make sense. 100 by 100 matrix is not well-representable. It will be showing you some of the matrix elements to give you some impression of your matrix. But what's actually sometimes quite useful is a graphic representation because it gives you some idea about the structure in the matrix.
21:01
So that's what I'm showing here for some random data. This is a 20 by 20 matrix. It's still relatively small. And you can just use from the Matlab library in show on the data. I define a color map, which is odd. That means it goes basically from black to white, or red, yellow, and so on.
21:21
And I don't use any nucleation. This is important to get well-defined squares which represent your data. And then you get all this random image in this case. But in your case, where you have a well-defined matrix with non-random data, you might have some structure
21:41
which is nice. Of course, now you can even plot a 200 by 200 matrix. No problem. And it would be difficult to represent this now really as numbers on the terminal. And you'd really have to analyze the data really
22:00
very carefully. Another application of random numbers, suppose I'm casting dice. That means I choose random numbers between 1 and 6. 7 is not included. And I'm doing this by throwing 100 throws with three dice.
22:31
And I basically ask, what is the distribution in the histogram?
22:42
So I have this matrix with three different dice. These are the throws. No. This is the histogram. You don't see the casts on it.
23:06
So these are the casts of the three different dice. Now I can ask, what is the distribution between the outcomes 1, 2, 3, 4, 5, 6 for the different kind of dice? The first one is the blue one, and so on.
23:22
And you see, well, it's more or less equal. You probably need to do so a bit more often. The dice have this bit more equilibrium.
23:41
Now we come back to the problem which we were discussing at the beginning, slicing. So we have an array. And we know that we can have different views on our array.
24:03
And one way to have a specific view on an array is by slicing. And slicing, in principle, works in the same way as with lists, except that we have several dimensions. So in one dimension, this is basically trivial, as usual.
24:20
The first element is index 0. Negative indices come from the end of the array. Slices have the form start, stop, step. And if you omit values, or if you omit start, it will start from the beginning. If you omit stop, it will go until ending, including the last element.
24:40
And steps will be one in all elements. So let's try to do that. We create an array, 0, 1, 2, 3, 4, 5, and so on, until 9. And now it's, again, your turn just to check that what you learned in the beginning for the list
25:03
still goes here. So please try to reproduce these arrays here by slicing the array. So you're going precisely the same way as before. So you can use the same thing we said before.
25:23
Higher dimensions will be more interesting.
26:01
A, 7, 8, 9, that starts at element 7. It goes all the way until the end. So 7 colon is enough. 2, 4, 6, 8.
26:20
A, we start at 2. Go to the end, so we omit that instead of 2. And finally, the other way around, it's A colon colon minus 1. OK?
26:44
Watch what we did for this at the beginning of the first session. Now, things are a bit more interesting in higher dimensions. So we are going to play a game. I'm showing you a matrix.
27:03
I'm not showing you the solution here. I'm showing you the solution. So you take this matrix. I show you the matrix. I show you which matrix elements you should select. I'll just highlight it. And it's your turn to develop the proper slicing.
27:22
So the main information which you need at this point is that for each direction, for each axis, for each dimension of the matrix, you need a slice. So in the simple space of just one matrix element, we have to specify the axis 0.
27:42
Axis 0 is this one here. I'll talk a little bit more about that as we go on. So this is column 0, 1, 2. So that would be 2. And then 0, 1, 2, 3, 4, 5. So I could write 2 comma 5.
28:01
Or if I see more easily that this is the number 3 column from the end, I could write minus 8. So let's try to do this. This is a 5A. So let's create an array. A is mp.a range of 4 key, so 3 shape, 5 comma 8.
28:31
Let's take a look at it. So that's precisely the array which I have shown in my presentation.
28:44
This is the array which I'm going to use now to exercise the slicing. Let's say 8, 2 comma minus 3. Then I get indeed 21.
29:15
And now the game starts. So, oops, what is that?
29:21
Ah, OK, I have one more example where I give the solution. But then the game really stops. I mean, you'll have to do some work about that. OK, so that's what I mentioned briefly. In this case, it was just one matrix element.
29:40
So here, we really have two slices. So what does it mean? We start at the beginning, because no number 2 here. Start here. Out 2, but not including the row number 3. We start here at the beginning, up 2, but not including the column number 5. OK? That gives us this array.
30:02
So let's try it on. Indeed.
30:24
Let's see if I might give you another solution. Now it's your turn. So, what about this policy?
30:42
Now, there's not a unique solution. There are various solutions possible here. Column minus 8. Column minus 8. So, column minus OK. Column minus 3 would start at the beginning.
31:03
But you're close. Try it out before you say it. But it is the same for others. They could try to correct this. But I mean, the idea is a good idea. I mean, obviously, it's easier to come from the back
31:20
than from the beginning. So, using the minus 3 is a good idea. You start with minus 3, minus 3. Yeah, it's minus 3, column, minus 3, column, exactly.
31:43
OK. So this was easy. Let's make it a bit more complicated. It's also easy. We'll get more complicated as we go on.
32:30
The first index is the number of the rows. We need all rows. That means what do we write as is minus for the rows?
32:42
Column. And there's just one column. The column number. Number 3. So column, comma, 3. You can do some more work. And it does work. Now you could say, OK, I'm writing something here. But in fact, this figure here was created by
33:02
putting in this slice. So you can be sure that this slice is really corresponding to this image. And you can try it out yourself, of course. OK. Let's try another one. It says simply we are doing more complicated things.
33:21
This is the one. We've got two complicated things.
33:44
Column, comma, and 3, 3, 6. So 3, 4, 6. 4, 5, 6. Right? And the same thing. You could have used minus as well, or minus 3, or so. OK. 1, 2, 3, 6.
34:09
It'll be more interesting in a couple of slides.
35:01
Rows first start with row number 1 in steps of 2. And column, you start with row number 0 in steps of 3. Column 2, column 2.
35:20
Column 1, column 3. And the 0 is strictly speaking not even needed, because the descent is starting at the beginning. So this would be good enough. One question about 1D arrays. Can 1D arrays be a column vector also? Yes.
35:42
Instead of, let's say, a shape 5, you can have a shape 1, comma, 5. Which would mean that there is a 0 direction and a 1 direction. And 1, comma, 5, you can have 5, comma, 1. We are coming to that as we go in.
36:04
Now this one here is so complicated that I hit you in the solution right away, because we are using something which we haven't discussed yet. But maybe I can try this out first, just to confirm that we have indeed these matrix elements.
36:26
And then my question would be, how can we explain this? Yeah, but what is the logic? I mean, OK, it's every cloud element, but why? I mean, this is no longer the slicing syntax.
36:42
This is what's known as fancy indexing, because it's not more fancy than the slices. So if somebody can confirm that this works, OK, then this cloud is passing to the solution. What's going on here? Which elements are selected? So we are creating a logical mask, which then has once,
37:04
when this condition is met, right? Yes. 0 and 4, or 2 and 4. And then if you just apply this mask to it, then all these elements where the condition is true, it works. Right. So first of all, take this apart what you just said.
37:22
If I say h percent 3 equals 0, this is in principle an array. So I'm doing an operation on each element of the array. So I get, as you just explained,
37:41
a matrix, a Boolean matrix, with elements true and false. And these elements are true. If the element in A is divisible by 3 without any rest. And what is selected, if I put an A bracket around it,
38:00
is precisely the matrix elements which are, this Boolean matrix has elements true. It doesn't have a two dimensional form anymore, but that's in general not possible, because if you do this fancy indexing, it's not at all true.
38:21
And actually you see it here, that in each line you have the same number of elements. So that cannot turn out. This is not of those ground matrix. Ready for an even more complicated example?
38:42
Oh, the solution actually is very simple, because here you have the coordinates of each element. Row 1, the elements 3 and 4. Row 2, the elements 2 and 5. And row 3, the elements 3 and 4.
39:01
Again, this won't be a two dimensional matrix. If you do that, and you get A of 1,
39:27
which was that this matrix elements, 11, 12, 18, 21, 27, and 28. So you see, indexing can be extremely flexible, whatever you like.
39:46
Are there any questions? I mean, what's really important here is slicing. Fancy indexing, I will use not as often as the regular slicing, so that's something
40:00
you can also cover and find if you really need it. Let's maybe look at the applications. Yeah? Or could I cast, for example, this Boolean mask into integer? Is it just an np.int?
40:20
Because this only works for single numbers, but not for matrices. Because when I have integers, then I could only multiply this mask to A, and then I would only have zeros where this condition is not met, for example. And one. So you want to put zeros in the places
40:42
where it's traditional? For example, when I have true and false, and I just would convert it to integer, then I would have ones and zeros, and then when we multiply this mask to A, then I would have the same form, or the same shape, but only the positions where one was multiplied, the number is still there.
41:02
OK, so let me see. I mean, what you would like to have. So let's, here we have our matrix A. OK. And now you want to change all elements which are not divisible by C, or which are divisible by C.
41:21
We can take this mask that we had, and then we would need to cast this into an integer. Why should I do this? If I understood you well, you wanted to manipulate the elements. Oh no, that was just a more basic question. Just how can I typecast the Boolean matrix, for example,
41:42
in something else? His question was, why would you want to do that? And the answer to that is, probably not for the reason you're after, because there's a different solution to that. That's what he was going to show. No, I wanted to know how to cast matrixes into an integer.
42:01
Let me see. This doesn't make sense, actually. Isn't there a cast method? Sorry, it is. I just tried this one, but it's different, so nothing like it.
42:27
There is no, there is an S. This is something, frankly, I do so rarely. I need to look it up. There is more common, is that you use this mask
43:12
to assign a certain value to the selected elements. That's more common.
43:21
But the convulsion is also less than that.
44:14
I mean, we already have integers. Is this one too? No, it's not so. I mean, in principle, there is a classic conversion.
44:42
Since I use it practically never, I don't know if I want it. But I mean, this is something we need to look up. But I think what's more important
45:00
is that you use such Boolean masks to select matrix elements for which you assign them. Let's try to do the example. The problem is to produce a list of prime numbers
45:25
by using the seat of Eratosthenes. And I'll show you how this works.
45:42
Basically, the idea is the following. You have a list of numbers, let's say, from 0 to 49. And you want to have all prime numbers on this list of numbers. Now, 0 and 1 are not prime numbers, so they are exceptional. And then you just go through this list
46:01
and you start with the first element, which is 2. And you cross out every second element because every second element is divisible by 2. Then you take the next element, which is 3, and you cross out every third element. Actually, you only start at 3 squared, at 9,
46:22
because the 6 was already crossed out because it's divisible by 2. So you can always start at the square of this number. Next number is 5, because of 25 and 35, and so on, up to 7. Since there cannot be another divisor, a relevant divisor,
46:44
larger than 7, because, let's say, 49 would be divisible by 11, if that were the case, which is not the case, of course. Then there would be another divisor, which is smaller. So we had already treated this case. We are finished here.
47:01
Everything which is left over are prime numbers. How do we solve such a situation by means of room priorities? And that's basically the example. So we have a maximum of 50.
47:21
We have an array running from 0 to 49. That's why the max is 50. So these are our integers. That's what I just showed you in this picture. That's just our list, our 1D array.
47:47
Then, in addition, we have a list which defines whether a given number is a prime number. A priority, we assume that all numbers are prime numbers,
48:01
because afterwards we are crossing out numbers. So, basically, the idea is all these are possibly prime numbers, but once we cross them out, we put the entry to false. So we know this number is not a prime number, 14 is not a prime number, and all elements in the end
48:21
which are still set to true are prime numbers. So, say we want to have an array of T Boolean to false, and since we want to have 1s, true, we have to take 1s.
48:41
I showed you before, if I do this with NP0s, T type Boolean, then I get all 4s. If I have 1s, I get all 2. So, in principle, all the elements from 0 to 49 are prime numbers. But we already know that the first two elements
49:00
are no prime numbers. So, that's the slice going from beginning to 2, which excludes the 2. And then we go to the rest. We start at 2, of all the indices, j from 2, up to the square root of the largest number.
49:22
If the number is a prime, then we have to cross out all multiples, starting at the square root. So, that's the situation where we can use our slicing. We start at this number squared,
49:40
in steps of this number. This is now precisely an application of the slicing syntax, which we just have used, where you might have asked yourself, why do we select these strange elements of a matrix? This is precisely such a situation. We select all the elements, for which we can now say, if j is a prime,
50:02
that these numbers are no primes. Starting at j squared, in steps of j, all these numbers which we can find, there are no prime numbers. Here, I print out the array is prime. Well, actually, integers is prime. So, this is now the expensive indexing.
50:23
I have a Boolean array, and only those elements of integers, where it's prime is true, the still potential candidates for a prime number are printed. So, when I run this, you can see successively how the number of potential primes is reduced to the very end
50:42
when only really prime numbers are left. And that's what I print out here. So, let's see. So, at the beginning, we have basically everything starting at true. Then, we identify two as the leading prime number here.
51:04
We start out at four, taking every second element away, and we are left with this array. It still, of course, has quite a few numbers which are not prime numbers, for example, 21. Then, the next number is three.
51:21
We start out at nine, in steps of three, crossing out all remaining elements, and so on, until we reach seven. The 49 is crossed out in the last step, and what's left are just prime numbers.
51:41
And this is, even though it, well, doesn't look that compact, but I mean, I would, in general, not have this line here, because that's just, let's say, for debugging purposes. And here, we just define zero and one out as prime numbers.
52:03
The main part is this one here, which is actually very simple. If I have identified a prime number, cross out the prime numbers, a little bit more into the numbers, starting at j squared instead of j. So, that would be the application of helium arrays,
52:22
of slicing, and of fancy indexing. So, this way, the things which we have just discussed can be applied in a practical example.
52:42
Another important aspect, which, to some extent, we have already discussed, but which, from my experience, occasionally causes problems in understanding our axes. In particular, if you go to a higher-dimensional matrix element, I mean, one-dimensional is trivial.
53:02
You just have one index in this one dimension. Two dimensions is also still okay, but in three dimensions, you have to know where you are, which plane you're talking about. So, it makes sense to talk a little bit about axes. So, if you are working with matrices,
53:22
then you basically know how the index notation for matrices works. Basically, it works like this. You have the element a11 here. The next element is a12, a13. So, the second index denotes the element. The first index denotes the row.
53:42
So, here in row three, we have all the elements a31, a32, a33. So, the first element is the row. The second element is the column. And it works precisely the same way in numpy. So, for numpy already,
54:01
well, the first element is the row. So, this is our axis zero, zero one, and this is our axis one. The only difference is that in type, we start with index zero. So, in a matrix, you don't do that.
54:20
You start with index one. You start with index zero. But the association of indices here with rows and columns works in just the same way. The first index is axis zero. This goes from top to bottom. And axis one goes from top to bottom. So, you can try this out
54:41
by taking an array and calculate the sum. There are actually different ways to calculate the sum of an array. You can calculate the sum of all matrix elements. Or you can calculate the sum across a certain axis. Let's take a look at that.
55:02
So, you create an array. Maybe not a quadratic array. So, then it's what doesn't matter because of the quadratic array. Let me create an array of elements.
55:20
Let me say comma four. The array looks like that. And now you can do the sum over everything. All the sum along axis zero it should be from top to down. It should give you four values. All the sum along axis one.
55:43
So, let's start by doing the sum along axis zero. So, in p dot sum of a axis equals zero. And you see you get four matrix elements.
56:01
One plus five plus nine is fifteen and so on. So, clearly this is axis zero. Whereas axis one is horizontal. p dot sum of a plus one is six. One plus three
56:23
plus three is six. Four plus five plus six plus seven is twenty-two. And eight plus nine plus seven plus seven is thirty-eight. You want to have the sum of everything. Just keep the sum of a and the sum of all
56:42
matrix elements. Six plus twenty-two plus thirty-eight is sixty-six. So, you have two axes and they are well defined. Axes zero is the first index. Axes one is the second index. And if you have higher dimensions and so on.
57:12
Sorry? You are summing all the problems. So, if you want to sum just one problem. Oh, if you want to
57:23
extract one of the values or? Yeah, I know. You can just write it for example zero. Oh, sure. You can take the subarray if you want. You can slice it. And you will get the sum only for that term. I mean, for example, you could
57:41
you could say a of zero and you get six. Now, let's go to higher dimensions. That's a bit more complicated. But actually, it's not that complicated.
58:01
So, this is an array with twenty-four matrix elements which is a two by three by four matrix. So, it's a three dimensional matrix. Try to represent it here. So, we have here two planes if you like. So, you see this red brackets.
58:20
They are the outer level and everything as next element these green parts here are the basically what's denoted by axis zero. So, the index of axis zero is zero for the plane here in front and one for the plane in the back.
58:42
And then axis one contains the rows contains here the entries zero, one, two, three four, five, six, seven and so on. So, you have this level structure, this on the entire structure. And if you realize
59:01
how that looks like and I'm giving up this image ready for the exercise. We briefly go to the exercise but then I'll be back to this image here. What you should do is try to make planes here. Like the front plane all the plane consisting of zero, one, two, three, twelve, thirteen, fourteen,
59:21
fifteen, or this plane here for example three, seven, eleven, fifteen, nineteen, twenty, twenty. Try to cut in various ways through this three dimensional array. So, what we do is we produce this array here.
59:40
It's precisely what I've shown you in the picture. And g a range of twenty-four v-shape, two, three, four. That's the three dimensional array which you can already see here. And now just try to
01:00:00
cuts through axis 0, axis 1, axis 2, and compare what you get with this image here. Just play a little bit around and try to do cuts in different directions.
01:00:34
This is not so important which cut we use exactly, but try to press into the planes together.
01:02:06
Take a look at it together on the ray and say for example in axis 0 we want to have element 0 and everything else in the other directions.
01:02:22
What does that mean? Well in axis 0 we take the plane 0, which consists of the front plane. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. It's just this plane. This is axis 0 here.
01:02:41
This would be index 0, this would be index 1. So we get this one. Now I'm doing the same thing for axis 1. So if I take index 0 for axis 1, I should have 0, 1, 2, 3, 12, 13, 14, 15.
01:03:04
This one. 0, 1, 2, 3, 12, 13, 14, 15.
01:03:26
And finally if I do the same thing for axis 2, this would be everything where axis 2 has index of 0. This would be 0, 4, 8, 12, 16, 20. 0, 4, 8, 12, 16, 20.
01:03:57
And of course I could use other indices depending on the size of the matrix.
01:04:04
But you see that in this way I can get cuts to the multidimensional array. And of course if you now have a ten-dimensional array, which the idea of the array looks like, but in principle by an understanding of the three-dimensional array no more or less which index is responsible for the array.
01:04:30
This here are the questions. Also coming to the last part of the tutorial.
01:04:53
And the important part here actually is that you have, I think for today, that you have seen certain things.
01:05:01
I think if you go out of this room and say okay, do not buy something I really have to look at that is useful, then that is what I want to achieve. Of course you have to go back to the documentation to look up things. There are lots of things which I cannot talk about today. But at least you should have an idea of what do not buy can be useful.
01:05:24
What is A of 0? So A of 0, well it just takes 0 as the index for the first axis because you do not get additional indices.
01:05:46
So that is the front plane of our array. And a bit more interesting is actually this one here. A dot dot dot comma 0. What is dot dot dot in everyday use?
01:06:04
Well it stands for everything else somehow. That is precisely what it is. Dot dot dot is for everything else. So the first index, the second index on the last index is 0. So that is precisely the same thing as this one here.
01:06:25
That is quite nice except that you are not allowed to use dot dot dot several times. So of course you can't do something like that.
01:06:43
Because there is no way you could figure out what you are building. But sometimes if you have an array, for some reason you don't know its dimension, you don't care. You don't care about the leading indices.
01:07:02
You can do something like that. But that is mostly for higher dimensional. Now we were already talking about doing operations on matrices in the sense of multiplying them by a number.
01:07:22
Or maybe adding numbers. And that is something which we need to explore in more detail. So I create two matrices. The first matrix, these are just one dimensional matrices. The first one is trying to be 0 to 3. The second from 4 to 7.
01:07:43
So supposedly you can add arrays. That is not very surprising. So you add arrays element by element. Like you would add vectors for example. Because this is what happens when you multiply them.
01:08:05
Now depending on your background you might have different expectations. Some of you might think it goes on a scalar program. Multiplying vectors on a scalar program. That is not what is happening.
01:08:22
Multiplication is always element wise. You could think this is special for one. No, it is not. Define to the arrays and multiply them. Please try it out just to see how it works.
01:08:41
Just define two very simple 2D arrays. Actually you can just reshape A and B if you like. And we will reshape 2,2 for example on these arrays here. Then you have two 2D arrays. And just multiply them.
01:09:44
So let's try this. I just reshaped these two arrays. I get two 2x2 arrays. They look nicely presented here. But you can see there is an array 0,1,2,3 and a number array 4,5,6,7. I am now going to multiply them.
01:10:05
And you see 0 times 4 is 0. 1 times 5 is 5. 2 times 6 is 12. 3 times 7 is 21. So this is definitely an element wise multiplication. It is not a matrix multiply.
01:10:23
Now you might say this is really disappointing. I want you to do linear algebra. Multiply matrices. Matrices to vectors and so on. We calculate scalar products. We calculate determinants. It would be great. 3x3 is already some value.
01:10:42
Calculating 4x4 matrices is really hard work. This should be done by the computer. So where is all the linear algebra? Oh, it is there of course. But let me just ask. Who is unfamiliar with matrix multiplication? There is no problem.
01:11:01
I am going to explain it. Don't be shy. Everybody knows matrix multiplication. Great. Okay. Then I assume that you really know it. So there are actually all ways to do matrix multiplication. You can do these blocks here.
01:11:22
They stand for matrix. So either you use np dot matrix A times matrix B. You can also use A dot dot of B. Which means multiply A by B. Or very recently.
01:11:41
This can be debated but that is a big advance. But that is a sort of quantification operator now. A at B. Doesn't make much quantification. So let's try that. But this really depends on having a relatively recent installation.
01:12:01
So we divide 3.5 by 3.5. At least one content which nowadays is no problem. So let's see. np dot of A comma B should always work. Let's check. Here the product is 676.1.
01:12:25
676.21. You could also say A dot of B. It's the same thing.
01:12:41
And you could as well do A and B. I think if the last command doesn't work then for some reason you either have an outdated Python or an outdated Python. So of course you can do a matrix multiplication.
01:13:03
You can solve it by vectors. You can solve it by vectors with the matrices. So let's do another example. Some practical example. Random walks. So this is basically simulating that you are going out tonight in Elan having 3 views, 4 views, I don't know how many views.
01:13:29
And at some point you are doing what we call a random walk. It means you do a step but in an arbitrary direction. You want to simulate how fast you get to your hotel.
01:13:42
If you know random walks you know that if you go at a constant speed you advance only with the square root of time, which is already much slower than the proportion of the time. And your direction might be pretty arbitrary. So hitting your hotel is even more unlikely. Maybe two views are enough.
01:14:01
Don't let me know. So let's try to simulate a random walk. But it's still more likely than if you always walk in one direction. Ok, so let's assume you do 10,000 steps.
01:14:21
And let's see, you tried this experiment five times. So suppose you were here for the tutorial for the conference the next two days and maybe even for the sprints. What would you do to solve that? Then you have five chances to walk home with the team up here. So let's have five conversations. So the idea is that we choose a random angle.
01:14:44
This will give us a matrix of size, shape, length or form. And the realization is a 10,000 by 5 matrix filled with random numbers. We multiply them by 2 pi. Because the angle goes from 2 to 2 pi.
01:15:01
We can walk in any direction. And then we produce an array in a quite interesting way. So we already have seen that in principle we can take an array and apply a function to the full array. So we take the cosine of all these angles.
01:15:24
And now we do a community sum. So we have an array. Suppose you have an array 1, 2, 3, 4. Maybe I'll show you here. Let's see how this works.
01:15:42
A range of 10 let's say. So the cumulative sum goes in the following way. This is 0, 1, 2, 3, 4, 5 and so on. So 0 plus 1 is 1. 1 plus 2 is 3. 3 plus 3. Maybe this is actually not a good sum. Because you are always adding the previous one.
01:16:11
Maybe that's how. So 0 plus 2 is 2. 2 plus 4 is 6. 6 plus, in this case 6 is 12.
01:16:21
12 plus 8 is 20 and so on. So it's always the partial sum from the beginning up to a given point. You add up these steps. That's what we did. And we do this in x direction and in y direction. So we take cosine and sum. And then we got the whole thing.
01:16:50
Hopefully you'll tell us somewhere here. So these would be random walks.
01:17:01
By the way nowadays there are people who don't like this code for a pretty strange reason. If you have item 3.6. Does somebody know the value of Tom?
01:17:25
Is one of the changes in item 3.6 maybe not the most important one? Nobody knows what that is?
01:17:45
It still doesn't exist in Numbi. So you could write the tau here. Now I understand what you're doing.
01:18:01
Exactly. That's the point. That's why 28th of June is now celebrated as the tau day. Because now people all of a sudden understand. Actually 2pi is much more often in Boble than in fly.
01:18:23
So it makes a lot of sense maybe. It's available in the math module and in the complex math module even. Where it makes maybe even more sense. So cosine and sine. I'll talk very early. Not too far. Anyway you see that since I didn't define the C I had restarted the problem responding to a question before.
01:18:42
So I don't have a fixed C now. And this figure will be different every time. Now I can also look at the distance from the origin. Hypothesis. So this is the distance we're making as a function of time.
01:19:03
And you could also look at the mean of the square. This should roughly go linearly. But this is distance squared. So if you take the square root you advance only the square root of the solution.
01:19:20
Ok so you see here. I mean look by arrays. Here in such situations you don't talk much about the slices. You just use arrays as objects. You operate the functions on these objects. And probably a guy will tell you in his sci-fi to talk a bit about special functions in sci-fi.
01:19:44
There are lots of special functions in sci-fi which also allow you to operate on arrays. And this makes code very readable. And actually in such a notebook when you're analyzing data which you have stored in arrays. This usually makes for pretty clear code.
01:20:04
But there's also an issue about this. Let me show that. Here we're going to time a few operations. So the idea here is that we define a range of numbers.
01:20:20
One million numbers here. The integer is from zero to one million minus one. And we want to calculate the square. How much time does it take? Now this is around several times to get 50,000 average. It takes about 1.3 milliseconds of time.
01:20:43
It might differ on your computer depending on the processor and so on. Now if you would do that with a list comprehension. Suppose you would generate a list where you go through this range here. And square each element in this range.
01:21:01
And put it in a list. How long would that take? It takes about 300 milliseconds. Now imagine it happens that occasionally you have a program that will run, let's say for a day. For the weekend.
01:21:21
Now the difference between 1.3 milliseconds and 300 milliseconds is almost a fact of 300. It really matters whether your program runs a day or 300 days. Or is that good with a pump which does all the work? I mean here you can gain a lot.
01:21:40
If this is really the pump, then you are losing your time. Let's do this for a sign. We could just use this array and evaluate the sign of all these values in here. Or we could try this comprehension and do it individually on every element of this range. So this is 3.3 milliseconds.
01:22:15
This is 17 milliseconds. This will look like a factor of 5.
01:22:21
So you see that here I can already give you by some advantage of speed. That depends a bit on how many elements you have in your array. But speed-wise you might have a significant advantage. Now one point which I could in any case address now.
01:22:44
That's kind of the problem. This broadcast. Maybe I'll briefly go through these. That's very brief. This is a list of operations which you can use on arrays. So you see you have all kinds of mathematical functions.
01:23:05
Some operations, complex numbers. There are a lot of different things. This line is mainly to suggest that you should go through the documentation at some point. And if you need something, you'll find it there.
01:23:25
More important because... There's an intersection between numpy and cypite functions. Is there any good choice? I think usually...
01:23:44
I'm not sure what you can say in general. Just try it out sometime. I mean these are different implementations anyway. And just try it out. What do the functions show?
01:24:03
I mean I couldn't say enough for all functions, but there are differences as well. What's really important to understand is broadcasting. I mean you have noticed that we were able to multiply a matrix by a factor.
01:24:22
You can also add a number to a matrix. Which in a sense is strange because we have said this works element-wise. And one number is actually a mini-arrays. How does it work? Well there is a key rule or set of rules for so-called broadcasting.
01:24:43
You can do this child operation. You can do this broadcast in the sense of... Then the arrays have exactly the same key. Every two arrays, if they are of the same size, no problem. The arrays all have the same number of dimensions.
01:25:03
And the length of each dimension is either a common length or one. I'm just saying this in more detail. This is just a list of environments. All the arrays that have too few dimensions can have their shapes to match with the dimension of length one. So basically you can blow up your small array to the size of the full array.
01:25:27
Now this sounds pretty complicated. I hope that the following images make this a bit easier. So I have an array of shapes three, four. Three rows, four columns.
01:25:42
So what actually happened that we multiplied NP once, an array of ones by ten before. Was actually the following. I have one ten. And this can be extended to the full shape of this array here. That's why it's called broadcasting. This cell broadcasts this to the other cells.
01:26:04
And now I can add these two or I can multiply them. This also works if the first dimension here, this one here, corresponds here. Then I can just broadcast in this direction.
01:26:21
This doesn't work if I have the three here. Now what should I do here? It doesn't fit these ones. Here I can just broadcast in the other directions. Here I cannot do that. It also works if I have shape three comma one. Then you see the three of these.
01:26:42
And the one instead of the four is possibly four. Then I can broadcast in this direction. So if you go back, either it has exactly the same shape or... Now let's read this again. The rays all have the same number of dimensions. And the length of each dimension is either a common length or one.
01:27:04
That's precisely what we have here. The dimensions are the same. And the shape entries are either the same, three, three, or one of them is one. Then you can broadcast in this way.
01:27:23
That's the requirement number two. Or the rays that have too few dimensions can have their shape represented with the dimension of length one. That is probably two. That is this one here. Four can be pre-pended by one.
01:27:40
Then I have an array of shape one comma four. And then I can put a little bit of one. Four is equal and the one and the three go fine because I can broadcast here. The three doesn't work because ones have to be pre-pended. So even if I prepend the one, one comma three doesn't fit at all this shape.
01:28:03
So that's how broadcasting works. And for beginning this is a place where one likely makes mistakes. So it's a good idea maybe to look again at these images if you encounter any problems.
01:28:20
At this point I'm running out of time. That's fine because at the end I just have a few applications. And let me just briefly look through them so that you have an idea of the interest the material will have to you. Actually in the GitHub repository for the exercises you will also find a notebook with solutions.
01:28:49
So if you are interested in understanding how such a situation can be solved, just go to this notebook and look at the solutions. They are not too complicated and might give you some idea.
01:29:02
I don't solve this problem, I just solve this problem from Mandelbrot. Calculation of pi by a simulation, linear algebra, eigenvalue problems. Just here for people interested in eigenvalue problems, and of course you can calculate eigenvalues, eigenvectors in a product or the product of vectors and so on.
01:29:27
There are some statistics routines. And also that might be interesting for some of you. Image processing, just by looking by arrays,
01:29:41
you can for example look up whether values in this image are above 128 or below and set to 0 or 1. You can put a frame around it. Remember, mask arrays has indexing. You can change the constants or you can put a mask here.
01:30:01
All these things can be easily done with NumPy arrays because as I mentioned at the very beginning, images are increased for also data arrays. You will find the solutions in the notebook.
01:30:37
So here we have downloaded these controller exercises.
01:30:41
There's also the notebook with the solutions. There's also the full presentation as a PDF. If you want to take another look at it, you're welcome to download all this. If you want to get the whole repository and you don't know how to work with GitHub,
01:31:00
tomorrow will be a tutorial. I think this is how we promote it. I'm giving a tutorial tomorrow on kids using version control, which is actually something which if you haven't used version control so far and you're doing program-developing, which I think is worth taking a look at, you can give a tutorial or not.
01:31:22
Version control is something that can be extremely helpful in practical work. So if you're around, you're very welcome. And if there are any questions, I'll be around for a full week. So please feel free to ask me any questions. Thank you very much for the attention.
01:31:40
I hope you have a successful work with NumPy.