## Category Archives: Matlab

## Introducing Community Profile Pages

*This week, guest-blogger David Wey welcomes the new community profile pages. David is a Senior Developer for MathWorks community sites.*

*by David Wey*

Have you ever wondered who created the file you’re looking at on the File Exchange, or who that nice person was that answered your question on MATLAB Answers? Maybe you thought to yourself *I wonder what else that person has done?* As of this week answering these questions got a lot easier.

**NEW PROFILE PAGES**

Our latest update to MATLAB Central includes new profile pages. These pages aggregate content from across all the MATLAB Central areas, thus easing the pain of having separate profile pages for each area (Answers, Cody, File Exchange, and so on). On these profile pages you’ll be able to see how active the person has been and how recently they’ve participated in the community. You will see all their answers, files, Cody problems, trends, and links.

To view someone’s new profile page, click on any author link wherever you see it, whether in Cody or the File Exchange. The popup displays a summary of information related to that area of MATLAB Central (such as the File Exchange or Answers). Click again on the user name to view the profile page or click on the other labels to see their submissions as a filtered search.

We hope you’ll enjoy the new profile pages and we welcome your thoughts and reactions. Check out some of your favorite community member pages, as well as your own, and let us know what you think in the comments below.

*Recommended article: **Chomsky: We Are All – Fill in the Blank.This entry passed through the Full-Text RSS service – if this is your content and you’re reading it on someone else’s site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.*

## Modeling with ODEs in Matlab – Part 5B

And so we reach the end. We will wrap up this series with a look at the fascinating Lorenz Attractor. Like the logistic map of the previous lesson, the Lorenz Attractor has the structure and behavior of a complex system. Unlike the logistic map, the Lorenz Attractor is defined by a system of first order autonomous ordinary differential equations. Thus, it is a perfect example to use for this last lesson where we examine the importance of error tolerance in evaluation chaotic systems of ODEs.

This is the second part of a two part lesson of a five part series. The first part of this lesson begins here. If you have not read the previous lessons in the series, I encourage you to start there (at least read through Part 2). Lesson 1 discussed the meaning of an Ordinary Differential Equation and looked at some simple methods for solving these equations. Lesson 2 looked at the Runge-Kutta approach to solving ODEs and showed us how to use Matlab’s built in function to do so. Lesson 3 looked at two sample multi-population ODE models and explored how to interpret ODE models of living systems. Lesson 4 examined non-linear optimization approaches to fitting ODE modeled systems to empirical data.

To begin, we need to define our ODEs. The Lorenz System is made up of the following three interrelated differential equations:

The equations are made up of three populations: *x*, *y*, and *z*, and three fixed coefficients: *sigma*, *rho*, and *beta*. Remembering what we discussed previously, this system of equations has properties common to most other complex systems. First, it is non-linear in two places: the second equation has a *xz* term and the third equation has a *xy* term. It is made up of a very few simple components. Although difficult to see until we plot the solution, the equation displays broken symmetry on multiple scales. Because the equation is autonomous (no *t* term in the right side of the equations), there is no feedback in this case.

This system’s behavior depends on the three constant values chosen for the coefficients. It has been shown that the Lorenz System exhibits complex behavior when the coefficients have the following specific values: *sigma = 10*, *rho = 28* ,and *beta = 8/3*. We now have everything we need to code up the ODE into Matlab:

% lorenz.m % % Imlements the Lorenz System ODE % dx/dt = sigma*(y-x) % dy/dt = x*(rho-z)-y % dz/dt = xy-beta*z % % Inputs: % t - Time variable: not used here because our equation % is independent of time, or 'autonomous'. % x - Independent variable: has 3 dimensions % Output: % dx - First derivative: the rate of change of the three dimension % values over time, given the values of each dimension function dx = lorenz(t, x) % Standard constants for the Lorenz Attractor sigma = 10; rho = 28; beta = 8/3; % I like to initialize my arrays dx = [0; 0; 0]; % The lorenz strange attractor dx(1) = sigma*(x(2)-x(1)); dx(2) = x(1)*(rho-x(3))-x(2); dx(3) = x(1)*x(2)-beta*x(3);

We can now quickly generate a solution. I have picked a starting point of **[10 10 10]** and I encourage you to play around with other starting points. Because this is a system of three equations, the solution can be plotted in three dimensions. Because the shape of the solution is somewhat complex, I created a script to generate a rotating animation of the shape. The following lines of code generate 60 separate png files (one for each frame).

% Generate Solution [t, y] = ode45('lorenz', [0 20], [10 10 10]); % Create 3d Plot plot3(y(:,1), y(:,2), y(:,3)); for i=1:60 view(6*i, 40); % Rotate the view set(gca, 'XLim', [-20 20]) set(gca, 'YLim', [-25 25]) set(gca, 'ZLim', [0 50]) % Remove the axes axis off % Generate the file name for the new frame name = sprintf('frames/frame-%02d.png', i); % Save the current figure as a png file using the % file name specified above. print('-dpng', name); end

I then use the Linux ImageMagick converter to combine the frames into a looping animated gif. This is a Linux command line command, not a Matlab command.

convert -delay 5 -loop 0 -resize 25% -depth 4 frame*.png lorenz.gif

Here is the result!

Pretty cool, huh? The weird horizontal ‘bouncing’ seen in the animation is an artifact of how Matlab scales up its figures to fit the size of the window frame.

Anyway, let’s take a look. This image actually shows very similar behavior to last lesson’s logistic map solution. Without testing, I will assure you that the behavior is similarly sensitive to initial conditions (although we will not explore this feature here). There is some interesting emergent behavior as we see an almost orderly orbit around two main basins of attraction. Finally we see that the system does seem to be bounded within a specific region of space. What makes this system a *strange attractor* (just like the logistic map) is that even though the system is bounded, the orbit *never exactly repeats itself*.

The last lesson focused on how complex systems are sensitive to initial conditions. It turns out that complex systems are just sensitive in general. This time we will look at how this system is sensitive to the relative error tolerance of the ODE solver itself, in this case ode45. If you haven’t yet, you should take the time to review Lesson 2 where I discuss variable step sized ODE solver algorithms and look at how to set the tolerances of Matlab’s ODE solver.

To quickly review, ODE solvers take a step by step approach to generating a numerical solution to the ODE in question. To do so, a solution is generated by a fourth-order approximation for a given step size. Then, an approximate measure of the error of this solution is generated by using a more accurate fifth-order solution. If the error is too large, the step size is shortened and the algorithm makes a new approach at a solution (just one that is closer to where it started this time). This repeats until a solution is generated that is within the desired error tolerance.

It turns out that Matlab allows you to choose how forgiving you want your solver to be. You can set the relative error tolerance (‘RelTol’) and the absolute error tolerance (‘AbsTol’). For this example I will simply change the relative error tolerance. The default relative error tolerance is 0.001. I will lower that tolerance down to 1e-6 and compare the two solutions. In the following examples, the blue solution is generated using the 1e-6 relative tolerance. We set the error tolerance using the odeset function. Then we evaluate the solutions while passing in the returned value from the odeset function. Make note that in this example, the two solutions are using the exact same set of equations and starting at the exact same point.

>> options = odeset('RelTol', 1e-6); >> [t,y] = ode45('lorenz', [0 50], [10 10 10], options); >> options = odeset('RelTol', 1e-3); >> [t2,y2] = ode45('lorenz', [0 50], [10 10 10], options); >> figure('Position',[100 100 800 600]) >> plot3(y(:,1),y(:,2),y(:,3), 'b', y2(:,1),y2(:,2),y2(:,3),'r') >> view(45, 40)

Here is our result:

As you can see, the two solutions do seem to diverge. You can see it somewhat clearly in the inner part of the orbits, where one shows mostly blue and the other red. Still, it’s tricky to see exactly how quickly and where the two diverge. To get a better look at it, we will split the 3D graph into three separate graphs, one for each dimension.

>> figure('Position',[100 100 900 900]) >> subplot(3, 1, 1) >> plot(t, y(:,1), 'b', t2, y2(:,1), 'r') >> xlabel('t') >> ylabel('x') >> subplot(3, 1, 2) >> plot(t, y(:,2), 'b', t2, y2(:,2), 'r') >> xlabel('t') >> ylabel('y') >> subplot(3, 1, 3) >> plot(t, y(:,3), 'b', t2, y2(:,3), 'r') >> xlabel('t') >> ylabel('z')

and again, here is our result:

Keep in mind that this is the exact same graph as the previous figure, just plotted differently. Here we can indeed see that the two solutions diverge very rapidly (although rapidly may be a misnomer as we are ignoring units in this lesson). Blue and red seem to diverge somewhere between time 5 and 10, and while they do come back into close proximity, they never join back together (just like our logistic map example).

How did this difference happen? Recall what I said about how a higher error tolerance forces the numerical solver to take smaller steps. In each case, the solver went from time 0 to time 50. But, let’s see how many steps each took to get there. We can simply look at the length of the output array of each:

>> length(t) ans = 10577 >> length(t2) ans = 2969

Thus, the same solver, solving the same equation, starting at the same starting point, took over 3.5 times as many steps than the default approach when using a higher error tolerance. Furthermore, not only did it take more steps and presumably generate a more accurate solution, after a short period of similarity, the more accurate solver generated a *completely different solution* than the default solver! The interesting question is to ask, how quickly did our `good’ solver diverge from the real solution? If there’s any lesson to take away from Part 5 of this series, it should be to always question the results of your numerical solutions to ODEs that describe complex and/or chaotic systems. It only takes small missteps for your solution to rapidly diverge from the actual solution.

That wraps up our series on ordinary differential equations in Matlab. Thanks for reading!

*This entry passed through the Full-Text RSS service – if this is your content and you’re reading it on someone else’s site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.*

## MATLAB Onramp

*In the last post, Wendy Fullam told us about MATLAB Examples, where you could see working examples and pick apart the code to see how they worked. But suppose you wanted more? Suppose you wanted an environment that could teach you, step by step, how to get started coding in MATLAB? If that’s the case, then Chaitanya Chitale has just what you need. Chaitanya is a MATLAB Training Content Developer at MathWorks.*

*by Chaitanya Chitale*

Are you new to MATLAB and looking for a way to get started? If so, check out the new MATLAB Onramp course.

MATLAB Onramp is an online course that provides a brief introduction to the MATLAB language. The course gives you hands-on MATLAB experience via the use of an integrated, web-based version of MATLAB, as shown below.

As you work through the course you can try out different solutions to the problems asked and get immediate feedback.

## Course content and duration

The MATLAB Onramp course covers the basics of importing data, manipulating arrays, creating visualizations, and much more.

The course takes approximately 2 hours to complete. However, you can take the course at your own pace. After starting it, you can leave and come back to it at any time.

## Ready to get started?

The MATLAB Onramp course is complimentary with your purchase of MATLAB. To get started, head over to the MATLAB Academy site: https://matlabacademy.mathworks.com.

You can also access the course from MATLAB R2014b by selecting Help → MATLAB Academy from the Home tab.

Interested in other training? Explore the other training courses that are offered by MathWorks.

*This entry passed through the Full-Text RSS service – if this is your content and you’re reading it on someone else’s site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.*

## Random Numbers in Matlab – Part II

This is our second post in our series on random numbers in Matlab. The first post can be found here. In this post, I will explain how to control the random number generation functions in Matlab and discuss alternatives for projects with stronger requirements for randomness, such as cryptography.

## Random number generation

Random number generation in Matlab is controlled by the rng function. This function allows the user to specify the seed and generation method used in random number generation as well as save the current settings so that past experiments can be repeated. By default, rng starts with a seed of zero and uses the Mersenne Twister generation method. Whenever Matlab restarts, the seed of rng is reset to zero, which means that the same random numbers will be generated in the same order every time Matlab is restarted. If avoiding this is desireable, use the ‘shuffle’ seed.

>> t = rng %Stores current settings of rng in t t = Type: 'twister' Seed: 0 State: [625x1 uint32] >> rand(1,4) %Generates a 1x4 random matrix with default initial %state ans = 0.8147 0.9058 0.1270 0.9134 >> rand(1,4) %Generates a 1x4 random matrix %(different from initial random matrix) ans = 0.6324 0.0975 0.2785 0.5469 >> rng(t) %Restore settings of rng >> rand(1,4) %New random matrix same as initial random matrix ans = 0.8147 0.9058 0.1270 0.9134 >> rng('shuffle') %Seed rng on basis of current time >> rng ans = Type: 'twister' Seed: 385954034 State: [625x1 uint32] >> rand(1,4) %New random matrix produced with new seed ans = 0.5706 0.9136 0.4043 0.8423

As demonstrated in the above code, the settings of the random number generator rng can be saved and restored. The type, seed, and state of rng can always be accessed as well.

## Alternatives to the Matlab rand function

The current version of Matlab uses the Mersenne Twister (MT) algorithm to generate pseudorandom numbers by default. Other algorithms can be selected with the rng function. The MT algorithm is used in many programming languages, including C++, Python, R, and Ruby, and is sufficiently robust for most engineering applications, such as Monte Carlo simulations. The rng function can generate pseudorandom numbers with other algorithms, including a combined multiple recursion number generator and a multiplicative lagged Fibonacci number generator.

To obtain numbers that are more random and independent, functions provided by various operating systems can be used. CryptGenRandom is the default Windows function used to provide random numbers that are meant to be sufficiently robust for cryptography. Despite being secret, the algorithm from Windows 2000 was found to be vulnerable to various attacks in 2007. In mid-2008, Microsoft released a patch to fix this vulnerability. Unix-like operating systems use /dev/random to generate random or pseudorandom numbers by harvesting entropy from the environment. This approach is also meant to be sufficiently robust for cryptography but has also been found to have flaws.

There are other pseudorandom and random number generators that are not linked to an operating system. The Fortuna algorithm can be used for cryptographic applications, but its use for engineering applications is unjustified because of its slow speed. The website Random.org claims to provide “truly” random numbers based on atmospheric noise. There is a Matlab script that can access random numbers from this site, which can be found on Matlab Central. If you use this script, remember that there is a quota of up to 1 million random bits for free usage.

In addition, there are other pseudorandom and random number generators that can be used for various numerical computing applications, which are beyond the scope of this blog post. In the next post, I will explain how to create more distributions by using the basic rand and randn functions provided by Matlab.

*This entry passed through the Full-Text RSS service – if this is your content and you’re reading it on someone else’s site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.*

## Random Numbers in Matlab – Part III

This is the final post in our series on random numbers in Matlab. In the first post, we discussed basic random number functions, and in the second post, we discussed the control of random number generation in Matlab and alternatives for applications with stronger requirements. In this post, we will demonstrate how to create probability distributions with the basic rand and randn functions of Matlab. This is useful in many engineering applications, including reliability analysis and communications.

## How to Create More Distributions

Although the basic version of Matlab only provides the uniform and normal distributions, other distributions based on these functions can be generated. The log-normal, Rayleigh, and exponential distributions will be produced below as examples.

The log-normal distribution is easily.created by taking Euler’s number (e) to the power of a normal random variable (randn).

>> mu = 0; %Mean of log(X) >> sigma = 0.25; %St. dev. of log(X) >> N = 1000000; >> nbins = 100; >> X = exp(mu + sigma*randn(N,1)); >> hist(X, nbins); >> xlabel('Value'); ylabel('Count'); >> title('Log-normal distribution')

The Rayleigh distribution is commonly used to model wireless communication channels and can be constructed easily in Matlab. A Rayleigh random variable is the square root of the sum of the squares of two independent normal distributions with zero mean (randn).

>> sigma = 0.5; %Scale parameter >> N = 1000000; >> nbins = 100; >> X1 = sigma*randn(N,1); >> X2 = sigma*randn(N,1); >> R = sqrt(X1.^2 + X2.^2); >> hist(R, nbins); >> xlabel('Value'); ylabel('Count'); >> title('Rayleigh distribution')

The exponential distribution models the time between events in a Poisson process and can be created using the uniform distribution (rand).

>> lambda = 0.1; %Rate parameter = 1/mean = 1/stdev >> N = 1000000; >> nbins = 100; >> X = rand(N,1); >> E = -log(X)/lambda; >> hist(E, nbins); >> xlabel('Value'); ylabel('Count'); >> title('Exponential distribution')

As shown in this post, creating distributions on the basis of the simple Matlab functions rand and randn is easy and requires only a few lines of code. This is highly useful for a wide range of engineering and scientific applications. I hope these posts have helped you learn about the Matlab random number functions and will enable you to apply them to your own work.

## MATLAB and Git

*This week we hear from Toshi Takeuchi about how to take advantage of MATLAB’s recent improvements to Git integration. Toshi is a Senior Marketing Manager at MathWorks.*

by Toshi Takeuchi

One of the new R2014b features that deserves your attention is Git integration. Git is a source control system (also known as version control or source code management system) that enables collaborative software development. Why does that matter to you? Programming is an essential skill in many technical fields even outside computer science, and some universities now offer software carpentry workshops to enhance coding skills for researchers. Source control is one of those essential skills in software carpentry.

Until now, you may have tinkered alone with code you needed for your project. However, there are other people who may be working on similar problems and they may be writing similar programs. Source control enables you to work with other people so that you don’t have to do it all alone. Collaboration lets you be more productive in other aspects of your project.

Even if you don’t care about such collaboration, wouldn’t it be cool to share your personal project and see other people using it? They may even fix bugs and improve your code for you!

GitHub is one of the most popular websites that host Git repositories. The best place to share your MATLAB projects is File Exchange because of its popularity with the MATLAB user community. And guess what – File Exchange is integrated with GitHub! Now you see the connection?

## Basic terminology

What is a Git repository? A repo (repository) is a directory that holds your source code and any associated files. Local repos are on your local drive, and the remote repos are on GitHub or other hosts, and you sync the local repos to remote repos as you write your code. You can start with either the local or remote repos, but in this example I am going to start with a remote repo.

The process looks like this for a single developer:

- Create or fork a repo on GitHub
- Clone the repo to your local drive – this is your local repo
- Add your files to the local repo
- Sync your local repo to remote repo
- Repeat this process to keep your source code in sync as you write more code
- Share your GitHub repo on File Exchange

## What is forking?

When you talk about Git, you cannot go without mentioning “forking”. In the simplest terms forking means copying someone else’s public repo on the remote server, rather than starting a repo from scratch. In practice forking is used as a way to contribute to the existing projects or to start a new project using an existing project as a starting point. Once you make changes to your forked project, you can send a merge request to the original developer, and your changes may be accepted and incorporated into the main project.

Forking enables a flexible distributed style of collaboration and number of forks you have on your project acts as a measure of popularity – similar to the count of likes or followers on Facebook or Twitter. The social aspect of forking is an interesting topic on its own, but we need to skip it for this post.

## Getting ready

Signing up with GitHub is easy – just click the *sign up* button on the homepage and follow instructions. A free account would do for now. You also need to download and install Git. Even though GitHub has GUI apps for Windows and Mac, you need to set up the command-line tool for use with MATLAB. You also want to follow these instructions for registering binary files with Git.

## Creating a repo

Creating a repo on GitHub is very easy – just follow these instructions. From this point on I will assume you named your repo *Hello-World* and initialized it with a README file. Please note that you can only create a public repo with a free account.

## Cloning the repo to your local drive with MATLAB

Until recently, you needed to use the command line tool for this step, but starting with R2014b we can just use MATLAB’s Current Folder window. No more Git commands like `git init`, `git status`, `git add`, or `git commit`!

Open your copy of MATLAB and create an empty folder. Right-clicking the empty space in the Current Folder window to bring up a contextual menu, and select *Source Control > Manage Files*.

This will open a new dialog box: *Manage Files Using Source Control*.

- For
*Select control integration*, choose*Git* - For
*Repository path*, click*Change*

You now see a new dialog box: *Select a Repository*. Copy and paste the URL of the remote repo you just created. You can find the URL in the right sidebar of your new repo on GitHub.

You choose either SSH or HTTPS depending on how you setup your authentication on GitHub.

Click *Validate*. You may be asked for your login password for authentication. You can close the dialog box when your path is validated.

Back in *Manage Files* dialog box, the *sandbox* should be already set to your current folder. All you need to do now is hit *Retrieve*.

You have now successfully cloned the remote repo to your local drive. Check your Current Folder window. You should see just one file – README.md, but with a green circle next to it. This is just a text file but you can apply wiki-like syntax called markdown to make it appear like a regular web page when viewed on GitHub. README serves as the front page of your repo on GitHub.

## Adding files to your local repo

Let’s add a new MATLAB script file *helloworld.m*. It will appear with a blank circle – it means it is not added to Git source control yet. To add it to Git, right-click on the file and select *Add to Git*. The empty circle changes to “+” symbol. When you modify a file already under source control, the symbol becomes a blue square.

## Taking a snapshot with commit

You can continue editing files as you like, but at some point, you want to take a snapshot of the edits you made. That’s when you do a commit. You can select any empty space in the Current Folder window to bring up the contextual menu and select *Commit to Git Repository*. This will bring up a dialog box where you can add your comment about the changes you made since the last commit. Comments will be helpful to keep to track of your changes and revert back to earlier commits if necessary.

## Synching your local repo to remote repo

When you commit, the snapshot is saved in the local repo, but it is also a good idea to mirror the changes to the remote repo as well. To do so, bring up the contextual menu by right-clicking an empty space in the Current Folder window and select *Push*. That will push your changes to the remote repo. You may need to enter your password.

## Branching and Merging

The real power of source control comes from the ability to create multiple branches from your project. By default, you have a branch called “master” in your repo. You can create a new branch from the master branch, makes changes, and then merge those changes back to the master. This mechanism is used for working on new experimental features without affecting the working code on the master. You can branch and merge in MATLAB but the details are beyond the scope of this post.

## Closing

If you have been curious about Git but put off by its complicated command line interface, Git integration in R2014b makes Git much more pleasant and approachable. I hope this quick introduction motivates you to take advantage of this new feature. When you do, please don’t forget to post your project to the File Exchange. To learn more about Git, it is actually helpful to start with reviewing the underlying concept about how Git works.

## Introducing MATLAB Examples

This week, guest-blogger Wendy Fullam is trumpeting the arrival of a new Support page feature. Wendy is the Technical Marketing Product Manager for MathWorks online support and website search program.

*by Wendy Fullam*

Have you ever found yourself thinking, “I wish there was a place where I could go to see a bunch of MATLAB examples…”?

MathWorks has just what you’re looking for. We just launched a big new feature on the Support page: MATLAB Examples. On it, you can discover thousands of code examples for MATLAB and Simulink: data manipulation, signal processing, machine learning, statistics, finance, computational biology, finance, you name it. Maybe you’ll even discover a few things that you didn’t know were possible.

MATLAB Examples is a single destination to find high-quality code examples, including those authored by both MathWorks staff and contributors to the File Exchange. Here’s what the main page looks like.

What can you do here?

You can browse by topic area:

You can search by keyword, and filter the results:

After finding an example that you want to use, you can quickly see what product contains that example:

or access the code:

You can also find related examples:

The Help Team at MathWorks hopes you enjoy the new interface and welcomes your thoughts and reactions. Check out the new area and then let us know what you think in the comments below!