I recently wrote about the relatively new Pause button on the Editor portion of the MATLAB Toolstrip. Let's pause again to think about how we can exploit the awesome Pause button on the toolbar.... read more >>

]]>I recently wrote about the relatively new Pause button on the Editor portion of the MATLAB Toolstrip. Let's pause again to think about how we can exploit the awesome Pause button on the toolbar.

I already told you how you might use this button, of course, while your code is running. But there's even more you can do than I mentioned earlier.

You can also

- do several related tasks,
**while the code is running**(i.e., a pause is not required)

- peek and see what's going on,
- then use
`profile on`, - continue,
- wait a bit,
- then pause again, and, finally,

- use
`profile report`

- open some other file to look at while the code is running
- set some more breakpoints
**while code is running**

and the right thing will happen. You can set the breakpoint by

- a right click of your mouse in the area in on the left in the editor that is green, then
- a breakpoint selection

What actions to you take while using the Pause button in MATLAB? Let us know here.

Get
the MATLAB code

Published with MATLAB® R2018a

For any human being love is one of the biggest source of joy, happiness...problems and puzzles. Today's guest blogger, Aldo Caraceto, one of my fellow Application Engineers from Italy, is going to convince you to approach it from a different angle.... read more >>

]]>For any human being love is one of the biggest source of joy, happiness...problems and puzzles. Today's guest blogger, Aldo Caraceto, one of my fellow Application Engineers from Italy, is going to convince you to approach it from a different angle.

I love music. One of my favourite songs is the popular Toto track *"Hold The Line"*. Very briefly, this song is about love and timing, as you may infer from the main chorus of the song: "Hold the line, love isn't always on time". Ok, it's not always on time, but can I predict when it will be? To answer this question, I've found a couple of insightful works, *"Strogatz, S.H. (1988), Love affairs and differential equations, Math. Magazine 61, 35"* and *"Eva M. Strawbridge, Romeo and Juliet, a Dynamical Love Affair"* which I've translated in MATLAB code. The mentioned papers answer a very simple question: how to express mathematically love dynamics, taking inspiration from *"Romeo & Juliet"* by W.Shakespeare. MATLAB may be a good friend to help us in examining the evolution of this relationship. An `ode23` solver has been used to solve the system of equations representing the story. The results are quite funny.

This first example examines the condition where each person’s feelings are only affected by the other. Besides, we want our Romeo not following the expected behaviour: in this case, he'll be a confused and confusing lover: the more Juliet loves him, the more he begins to dislike her, generating surprising reactions with regards to the original tragedy.

$\frac{dr}{dt} = - a \cdot j,$

$\frac{dj}{dt} = b \cdot r$

In the system of differential equations representing the phenomenon, `a` and `b` are real, positive numbers, and measured in 1/time, hence are frequencies: the bigger they are, the shorter in time will be the swing of emotions for the two lovers. In addition, just a quick summary of the variables represented in the plots:

`R(t)`= Romeo’s feelings for Juliet at time t .`J(t)`= Juliet’s feelings for Romeo at time t.`R(t), J(t) > 0`signify love, passion, and attraction.`R(t), J(t) < 0`values signify dislike.`R(t),J(t) == 0`signifies indifference.

a = 2e-1; b = 5e-1; loveRJ = @(t,y) [-a*y(2); b*y(1)];

Now, we can set the problem up, collect data, and plot results, adding some annotations:

tstart = 0; tfinal = 50; tspan = [tstart tfinal]; y0 = [-1;2]; % initial conditions [t,y] = ode23(@(t,y) loveRJ(t,y),tspan,y0); plot(t,y') ax = gca; ax.XLim = [0 50]; ax.YLim = [-3 3]; ax.XLabel.String = 'Time'; ax.YLabel.String = 'Emotions'; ax.Title.String = 'Romeo & Juliet''s relationship'; legend('Romeo','Juliet')

In our first example, we have described the story with the changing emotions felt by Romeo and Juliet as they feed on each other's passion and indifference while the time is passing by. As you know, things - and people - are never so simple. Let's try to describe the relationship between Romeo and Juliet a bit differently, trying to compare the first, simple representation of the relationship with a more complex version. Then, we'll plot them together.

The new mathematical model can be expressed as:

$\frac{dr}{dt} = a \cdot r + b \cdot j ,$

$\frac{dj}{dt} = c \cdot r + d \cdot j$

As you may notice, this time there are four parameters, because we'd like to consider also how Romeo and Juliet are influenced by their own feelings:

a = -0.15; d = 0.17; b = 0.9; c = -0.9;

We calculate the solutions for the two relationship model (you may find the model definitions at the end of the article):

```
tstart = 0;
tfinal = 50;
tspan = [tstart tfinal];
y0 = [1.00;-0.5]; % initial conditions
[t2,y2] = ode23(@(t,y) loveRJ_simple(t,y,a,d) ,tspan,y0);
[t1,y1] = ode23(@(t,y) loveRJ_ownEffect(t,y,a,b,c,d) ,tspan,y0);
```

and we plot them all on the same axis

figure ax1 = subplot(2,1,1); % simple plot plot(ax1, t1,y1') ax1.YLim = [-2 2]; ax1.XLabel.String = 'Time'; ax1.YLabel.String = 'Emotions'; ax1.Title.String = 'Romeo & Juliet''s relationship - simple'; legend('Romeo','Juliet') ax2 = subplot(2,1,2); % complex plot plot(ax2, t2,y2') ax2.YLim = [-1.5 1.5]; ax2.XLabel.String = 'Time'; ax2.YLabel.String = 'Emotions'; ax2.Title.String = 'Romeo & Juliet''s relationship - self-effect(complex)'; legend('Romeo','Juliet')

Here we've seen the impact of different models on the evolution of emotions; it looks like the chosen values tend to reduce the frequency of changes in emotions. Let's call it self-control (or selfishness).

Phase plane analysis is a very important technique to study the behavior of dynamic systems; it covers a particularly relevant role in the nonlinear case, where widely applicable methods for computing analytical solutions are not available. In a nutshell, it basically consist of drawing the derivatives of solutions against the solutions in the phase plane. The derivatives of solutions are usually drawn in form of vector fields, to emphasize how large are changes in the solutions at a specific point in the phase plane and show the trajectories of the solutions, given specific initial conditions. Therefore, by superposing the two plots, it is possible to infer how the solutions might evolve, for the purposes to build our understanding under which conditions a system might stable or not.

We start calculating the derivatives `y1'` and `y2'` for each point of the phase plane. We create a grid of points where we want to draw out plots:

y1 = linspace(-10,10,20); y2 = linspace(-10,10,20);

`meshgrid` creates two matrices: one for all the uu-values of the grid, and one for all the vv-values of the grid. Then, we consider `x1` and `x2` matrices: `x1` will contain the value of `y1'` at each uu and vv position, while `x2` will contain the value of `y2'` at each uu and vv position of our grid.

[uu,vv] = meshgrid(y2,y1); x1 = zeros(size(uu)); x2 = zeros(size(vv));

Now we compute the vector field and plot the phase portrait. Our derivatives are computed for each point (y1, y2) at `init_time = 0`, through a `for` loop. We have obtained the phase portrait.

a = -2e-1; b = 5e-1; init_time=0; loveRJ = @(t,y) [a*y(2); b*y(1)]; for i = 1:numel(uu) Yder = loveRJ(init_time,[uu(i); vv(i)]); x1(i) = Yder(1); x2(i) = Yder(2); end

Finally we compute a couple of solutions and plot them, along with the phase portrait, on the phase plane.

figure quiver(gca,uu,vv,x1,x2,'r'); xlabel('Juliet Emotions'); ylabel('Romeo Emotions'); axis tight equal; % Calculate and plot 1st Solution tstart = 0; tfinal = 50; tspan = [tstart tfinal]; y0_1 = [2;-1]; % initial conditions [t,y1] = ode23(@(t,y) loveRJ(t,y),tspan,y0_1); figure(gcf) hold on plot(y1(:,2),y1(:,1),'b') plot(y1(1,2),y1(1,1),'mo',... % starting point 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 1 .63],... 'MarkerSize',10) plot(y1(end,2),y1(end,1),'bs',... % ending point 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 .63 1],... 'MarkerSize',10) % Calculate 2nd Solution y0_2 = [4;1]; % initial conditions [t,y2] = ode23(@(t,y) loveRJ(t,y),tspan,y0_2);figure(gcf) plot(y2(:,2),y2(:,1),'c') plot(y2(1,2),y2(1,1),'ko',... % starting point 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 1 .63],... 'MarkerSize',10) plot(y2(end,2),y2(end,1),'bs',... % ending point 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 .63 1],... 'MarkerSize',10) hold off title("Two solutions plotted on vector field")

This is the first model of their relationship, just dependent on the `a` / `b` parameters, defining Romeo's / Juliet's attraction for her/his counterpart.

function dy = loveRJ_simple(t,y,a,b) dR = a*y(2); dJ = b*y(1); dy = [dR;dJ]; end

In the second model of relationship, two additional parameters appear:

`a,d`= how Romeo, Juliet are influenced by their own feelings;`b,c`= Romeo's, Juliet's attraction for her/his counterpart.

function dy = loveRJ_ownEffect(t,y,a,b,c,d) dR = a*y(1) + b*y(2); dJ = c*y(1) + d*y(2); dy = [dR;dJ]; end

Today we have taken some steps in the analysis of this ''special'' dynamic system. Others can be done, exploiting tools already available in MATLAB. For example, making the system even more realistic, using the same ODE solver would have been a good deal or would you have chosen another one and why? Do you think calculating eigenvalues would have shed some more light on your understanding of the system? How would you do it in MATLAB? Try to answer these questions and ask yourself some new ones! Let us know what you think here.

Get
the MATLAB code

Published with MATLAB® R2018a

Today I'd like to introduce a guest blogger, Stephen Doe, who works for the MATLAB Documentation team here at MathWorks. In today's post, Stephen discusses how, and why, you might want to update your code to accept string arrays as inputs.... read more >>

]]>Today I'd like to introduce a guest blogger, Stephen Doe, who works for the MATLAB Documentation team here at MathWorks. In today's post, Stephen discusses how, and why, you might want to update your code to accept string arrays as inputs.

In R2016b, MATLAB® introduced the `string` data type as a new data type for text. Each element of a string array stores a sequence of characters. You can use standard array indexing and operations on string arrays, along with string manipulation functions introduced in R2016b. Also, you can use many MATLAB functions (such as `sort` and `unique`) on string arrays.

Here's a short example. Start with some text you can store as one string--or as a string *scalar*, a term we use to describe a string array with one element. As of R2017a, you can use double-quotes to create a string. (Single-quotes still create a character vector.)

```
str = "A horse! a horse! My kingdom for a horse!"
```

str = "A horse! a horse! My kingdom for a horse!"

If you use the `split` function to split that string on space characters, then the result is a string array with nine elements. Instead of getting a cell array, you get a homogeneous array storing text--an array that has the same data type you started with. The `split` function returns the string array as a column vector. Let's reshape it as a row vector of strings for more compact display.

str = split(str); str = str'

str = 1×9 string array Columns 1 through 8 "A" "horse!" "a" "horse!" "My" "kingdom" "for" "a" Column 9 "horse!"

String arrays now provide a powerful way to deal with text in your data. As you work with your text in a string array, you never have to resort to cell arrays or curly brace indexing. I won't belabor the point, because Loren already has published some wonderful guest posts on using string arrays. If you are looking for more examples using strings, see: Introducing String Arrays, Singing the Praises of Strings, and Working with Text in MATLAB.

And of course, you can find the documentation for string arrays at Characters and Strings.

A few paragraphs ago, I said that "many" MATLAB functions now accept string arrays as inputs arguments. In fact, in a future release nearly all MathWorks® products will work with string arrays as inputs.

Here's what we mean when we say that a product "works with" string arrays as inputs:

- If an input argument can be a single piece of text, then you can specify it as a character vector
**or**as a string scalar. That is, you can use either single-quotes or double-quotes.

- If an input argument can contain multiple pieces of text, then you can specify it as a cell array of character vectors
**or**as a string array.

We're holding to this pattern in old functions where we are adding support for string arrays, and in new functions going forward. Consider the `split` function I used to split a string. It works just as well on character vectors or cell arrays of character vectors as it does on strings. (Note that functions which have always returned a character vector in previous releases, such as the `fileread` function, will continue to do so for compatibility.)

We think this approach is the most seamless way to support use of string arrays throughout our products. Our advice is to take the same approach in your own code. If you maintain code of your own, or write code for other MATLAB users, then it is to your advantage to update your code to accept string arrays as inputs, while maintaining support for the older types for storing text.

Right now, you are thinking, "Great! But how do I do that?" (Well, perhaps "great" is not the exact word that came to mind.)

To help you update your code, the R2018a documentation provides guidelines to Update Your Code to Accept Strings. You can apply these guidelines to your code now. The guidelines, and our documentation, also provide links to helper functions, such as `convertStringsToChars`, that smooth the way to accepting strings in your code.

Here is a short example that shows two ways to put these guidelines into action. I'll start with a fast and simple way that uses one of our helper functions. Then I'll follow with another way that is a little more time consuming, but is also a little more forward-looking.

Suppose this code is your original function to abbreviate the name of a city using its first three letters, making those letters uppercase. Up to now, you have specified a city's name as a character vector. For example, if the input argument is `'Boston'`, then the output argument is `'BOS'`.

function abr = abbreviateName(str) abr = upper(str(1:3)); end

If your user instead specifies the **string** `"Boston"` as the input argument, then there will be a syntax error. For a string array, the syntax `str(1:3)` means, return the first, second, and third strings as a three-element string array. But `"Boston"` all by itself is a 1-by-1 string array!

One way to support both character vectors and strings is to use the helper function `convertStringsToChars` at the beginning of the original code. `convertStringsToChars` processes an arbitrary number of input arguments and, if any of them are strings, converts them. It leaves all other data types alone.

function abr = abbreviateName(str) str = convertStringsToChars(str); abr = upper(str(1:3)); end

With the helper function, you can accept input string arrays without altering any of the code that follows. Also, the output argument type does not differ from the type returned by the original code.

A second way is to use one of the new functions for text manipulation, such as `extractBefore`. These new functions also work with character vectors and cell arrays of character vectors. And so, this new version of `abbreviateName` works the same way for inputs of any text data type.

function abr = abbreviateName(str) abr = extractBefore(str,4); abr = upper(abr); end

While this code supports both strings and character vectors, I did have to rewrite the code. Also, this code returns a string if the input is a string. The original code always returned a character vector.

Which way is the right way for you? Well, that is the "choose your own adventure" part. If you are doing a lot of work with text, then it might be time for you to do a deep dive into your code and rewrite its internals to use string arrays. If not, then use `convertStringsToChars` and minimize the pain of updating your code. On either path, look for help in our guidelines.

And if you have things to say about string arrays, or your efforts to update your own code, then let us know here.

Get
the MATLAB code

Published with MATLAB® R2018a

load creds.mat connection = twitter(consumerKey,consumerSecret,accessToken,accessTokenSecret); % 100 is the maximum number of tweets that can be pulled at a time response = search(connection,'mathworks','count',100,'lang','en')

response = ResponseMessage with properties: StatusLine: 'HTTP/1.1 200 OK' StatusCode: OK Header: [1×26 matlab.net.http.HeaderField] Body: [1×1 matlab.net.http.MessageBody] Completed: 0Each status contains information about a single tweet, such as the number of likes, when the tweet was posted, and the text of the tweet.

```
% extract each status as a string
tweets = cellfun(@(x) extractBefore(string(x.text),50), response.Body.Data.statuses);
tweets(1:3)
```

ans = 3×1 string array "listening to NPR and there's a mathworks ad? :thi" "RT @MetrowestSTEM: Thank you @MathWorks, Underwri" "Basics of eigenvalues and eigenvectors with MIT P"I was looking for tweets from a specific user. The syntax for queries that are more advanced than just a search string can be found in the Twitter documentation. This query takes the form

pctencode = @(str) replace(char(java.net.URLEncoder.encode(str,'UTF-8') ),'+','%20'); st = pctencode('from:mathworks')

st = 'from%3Amathworks'

response = search(connection,st,'count',100,'lang','en'); tweets = cellfun(@(x) extractBefore(string(x.text),50), response.Body.Data.statuses); tweets(1:3)

ans = 3×1 string array "#HardTech Is it possible to add EtherCAT Master t" "Uses #drones and kites as #renewable energy sourc" "Are We Taking the “U” Out of UX? - What is a UX d"Several months and 1033 tweets later, here is what I found.

data = readtable('someTrumpTweets.csv','TextType','string'); data = table2timetable(data);Let's take a quick peek at the numeric data.

subplot(2,1,1) plot(data.whenTweeted,[data.retweetsNo,data.likesNo],'o') legend('Number of Retweets', 'Number of Likes', 'Location','northwest') axis('tight') subplot(2,1,2) plot(data.retweetsNo,data.likesNo,'o') xlabel('Number of Retweets') ylabel('Number of Likes')It turns out that the number of retweets and number of likes are highly correlated, so we can remove the number of retweets. In R2018a, functionality to work more easily with table variables was added, including the

```
data = removevars(data,'retweetsNo');
```

I also looked at whether the time of day or day of the week had any effect on the popularity of a tweet. This was easy with the % number of tweets by hour of day byHour = groupsummary(data(:,'likesNo'),'whenTweeted','hourofday'); figure bar(0:23,byHour.GroupCount) xlabel('Hour of the Day') ylabel('Total Number of Tweets') title('Number of Tweets By Hour of the Day')After about five months of data collection, I realized that I had introduced systematic bias into my data. Tweets that are up longer have had more time to collect likes. While the Twittersphere moves quickly, I observed that weekend posts were getting a lot more likes than weekday ones. This was in part because I collected data several times a day... during the workday. This meant weekend tweets would naturally have more time to accumulate likes. Luckily, I had been stashing my raw data from each pull for reproducibility, so I was able to go back and correct this. I merged datasets, keeping likes from the latest recording available. This is not perfect, but each tweet had a few days to collect likes. After adjusting for the bias, we test for statistical significance using

data.wkEnd = isweekend(data.whenTweeted); boxplot(data.likesNo,data.wkEnd,'Labels',{'Weekday' 'Weekend'}) ylabel('Number of Likes') title('Weekday vs. Weekend')

```
% test for statistical significance
ttest2(data.likesNo(data.wkEnd),data.likesNo(~data.wkEnd))
```

ans = 1

tweetDocuments = tokenizedDocument(data.tweets,'DetectPatterns',{'at-mention','hashtag','web-address'}); tweetDeets = tokenDetails(tweetDocuments); tweetDeets(37:39,:)

ans = 3×4 table Token DocumentNumber LineNumber Type ________ ______________ __________ ___________ "Jersey" 2 1 letters "." 2 1 punctuation "#MAGA" 2 1 hashtag

```
hashtags = tweetDeets(tweetDeets.Type == 'hashtag',:);
wordcloud(hashtags.Token);
```

Not only does looking at the hashtags give us an idea of what President Trump is tweeting about (#taxreform, #fakenews, #maga), but we see some abbreviations that represent common phrases he likes to use. I used the custom function below, % make everything lower case cleanDocs = lower(tweetDocuments); % replace hashtag abbreviations with standard language cleanDocs = replaceHashtags(cleanDocs);As of R2018a, we can create bags of N-grams, which enables us to look at phrases rather than just individual words. I first did a little processing to remove some noise in the form of punctuation or words that don't tell us much about the content.

% erase punctuation cleanDocs = erasePunctuation(cleanDocs); % remove common words before analysis cleanDocs = removeWords(cleanDocs,stopWords); % remove two letter words cleanDocs = removeShortWords(cleanDocs,2); bag = bagOfNgrams(cleanDocs,'NgramLengths',3); w = wordcloud(bag);

bag2Model = bagOfWords(cleanDocs); % set seed for reproducibility rng(123) numTopics = 18; mdl = fitlda(bag2Model,numTopics,'Verbose',0); [~,topics] = max(mdl.DocumentTopicProbabilities,[],2); data.topics = topics;Not every tweet fits perfectly into one of eighteen well-defined topics. To help me label the topics, I removed some of the noise by excluding tweets classified with the lowest confidence.

```
p = mdl.DocumentTopicProbabilities; maxs = max(p,[],2); cutoff =...
quantile(maxs,.5); dataTrimmed = data(maxs>=cutoff,:);
```

for ii = 1:numTopics figure wordcloud(dataTrimmed.tweets(dataTrimmed.topics == ii)); endFinally, let's get the average number of likes by topic so we can look at the four most and least popular topics.

popCats = groupsummary(data(:,{'likesNo','topics'}),'topics','mean'); load topicNames.mat bar(topicNames, popCats.mean_likesNo); title('Popularity by Topics') ylabel('Number of Likes')In the word cloud below, the most popular topic looks like a collection of subjects that includes the FBI investigation and Hillary Clinton. The next three most popular topics are clearer: NFL players kneeling during the national anthem, fake news, and tweets about North Korea.

[~,idx] = sort(popCats.mean_likesNo,'descend'); rank = ["The" "Second" "Third" "Fourth"]; nGrams = [1 2 1 2]; for ii = 1:4 subplot(2,2,ii) bag = bagOfNgrams(cleanDocs(data.topics == idx(ii)),'NgramLengths',nGrams(ii)); wordcloud(bag); text = rank(ii) + " Most Popular, N-Grams = " + nGrams(ii); title(text) endNow let's create word clouds for the four least popular topics defined by the

nGrams = [2 2 1 2]; for ii = 0:3 subplot(2,2,ii+1) bag = bagOfNgrams(cleanDocs(data.topics == idx(end-ii)),'NgramLengths',nGrams(ii+1)); wordcloud(bag); text = rank(ii+1) + " Least Popular with N-Grams = " + nGrams(ii+1); title(text) end

function cleanTweets = replaceHashtags(tweets) % custom function used in "What are all the tweets about?" to replace % hashtags with full expressions cleanTweets = tweets; oldFN = "fakenews"; newFN = "fake news"; cleanTweets = replace(cleanTweets,oldFN,newFN); oldHH = string({"hurricaneharvey"}); newHH = "hurricane harvey"; cleanTweets = replace(cleanTweets,oldHH,newHH); oldNK = string({"northkorea" "noko"}); newNK = "north korea"; cleanTweets = replace(cleanTweets,oldNK,newNK); oldTR = string({"taxreform"}); newTR = "tax reform"; cleanTweets = replace(cleanTweets,oldTR,newTR); oldPR = string({"puerto rico"}); newPR = "puerto rico"; cleanTweets = replace(cleanTweets,oldPR,newPR); oldPRs = string({"prstrong"}); newPRs = "puerto rico strong"; cleanTweets = replace(cleanTweets,oldPRs,newPRs); oldStand = string({"standforouranthem"}); newStand = "stand for our anthem"; cleanTweets = replace(cleanTweets,oldStand,newStand); oldMAGA = string({"maga"}); newMAGA = "make america great again"; cleanTweets = replace(cleanTweets,oldMAGA,newMAGA); oldAF = string({"americafirst"}); newAF = "america first"; cleanTweets = replace(cleanTweets,oldAF,newAF); oldTC = string({"taxcutsandjobsact"}); newTC = "tax cuts and jobs act"; cleanTweets = replace(cleanTweets,oldTC,newTC); endPublished with MATLAB® R2018a ]]>

Today I’d like to introduce a guest blogger, David Garrison, who is a MATLAB Product Manager here at MathWorks. Dave will talk about an exciting new contest for students and faculty where you can win a cash prize by showing us what you can create using the Live Editor in MATLAB Online.... read more >>

]]>Today I’d like to introduce a guest blogger, David Garrison, who is a MATLAB Product Manager here at MathWorks. Dave will talk about an exciting new contest for students and faculty where you can win a cash prize by showing us what you can create using the Live Editor in MATLAB Online.

Hello everyone. Loren has been kind enough to let me use her blog to tell you about the MATLAB Online Live Editor Challenge. The challenge is open to students and faculty of any college, university, or degree-granting institution. It's an opportunity for students to win up to $750 and for faculty to win up to $1000. Simply show us how you would use the Live Editor in MATLAB Online to create a live script on a topic of interest to you.

For students, pick a topic you've learned about in a class or from a research project or pick a concept in science, engineering, math or anything else that interests you.. For faculty, select a topic in your area and show us how you would teach that topic using a live script. You can work individually or in teams and submit as many entries as you want. We’ll judge each entry on things like presentation clarity, topic uniqueness, creativity, and effective use of Live Editor features. If your entry is a winner, we'll feature your live script on our website and you'll receive a cash prize.

For the challenge you'll be using MATLAB Online to create and share your live script. With MATLAB Online, you can use the latest version of MATLAB in your a web browser without installing, configuring, or managing any software. You can check your eligibility to use MATLAB Online here.

Here's an example live script that I wrote in MATLAB Online for estimating sunrise and sunset times.

To enter the MATLAB Online Live Editor Challenge, follow these three easy steps.

- Submit an entry form. Don't forget to do that because we can't consider your entry without it.
- Use the Live Editor in MATLAB Online to create an original live script on a topic of your choice.
- Put your live script and any supporting files in a folder in MATLAB Online, then share that folder with studentcompetitions@mathworks.com.

That's all you have to do. The deadline for entries is June 29, 2018 (7 a.m. ET). For complete details and contest rules, go to www.mathworks.com/academia/student-challenge/matlab-online-live-editor-challenge.

Good luck! We look forward to seeing what you create with the Live Editor in MATLAB Online.

If you have any questions about the MATLAB Online Live Editor Challenge, please let us know here.

Get
the MATLAB code

Published with MATLAB® R2017b

Sometimes it's nice to have a best friend. Sometimes I have more than one, context-dependent. I want to share my best friend today for dealing with `struct` arrays.... read more >>

Sometimes it's nice to have a best friend. Sometimes I have more than one, context-dependent. I want to share my best friend today for dealing with `struct` arrays.

Structure arrays are a useful way to collect similar information for a collection of items, even if what gets collected is not always the same size. However, struct arrays can also be cumbersome to work with. Thanks to the `table` datatype, I can now avoid some of the intricacies of indexing into struct arrays by simply performing a conversion to `table` first, and then using good, old-fashioned, stands the test of time, MATLAB indexing.

Some examples for working with struct arrays after converting to a table include:

- output of
`dir`- (I can then remove dirs, etc. very easily) `jsondecode``regionprops`from Image Processing Toolbox - (now includes output to`table`option)

I'll now get the listing for the blog post directory for one of my guest authors, Alan Weiss.

```
dirstruct = dir('AlanW')
```

dirstruct = 5×1 struct array with fields: name folder date bytes isdir datenum

And here's a picture from the Windows Explorer

You can readily see that I really have only 3 items, and not the 5 suggested in `dirstruct`. I can, of course, now look at the names. I extract them via a comma-separated list.

dirstruct.name

ans = '.' ans = '..' ans = 'Clumping' ans = 'FinSymbolic' ans = 'Sudoku'

and now you can see that I really don't care about the first two. But I'd have to delete these from the name field, and the folder field, and ... So I definitely can do so, but what a hassle.

Instead let me convert to a `table`.

dirtable = struct2table(dirstruct)

dirtable = 5×6 table name folder date bytes isdir datenum _____________ ___________________________ ______________________ _____ _____ __________ '.' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 '..' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 'Clumping' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 'FinSymbolic' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 'Sudoku' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05

And now I can eliminate the first 2 rows in the usual way in MATLAB:

dirtable(1:2,:) = []

dirtable = 3×6 table name folder date bytes isdir datenum _____________ ___________________________ ______________________ _____ _____ __________ 'Clumping' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 'FinSymbolic' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05 'Sudoku' 'C:\Work\ArtofMATLAB\AlanW' '22-Sep-2017 02:50:46' 0 true 7.3696e+05

I'm wondering if you've used struct arrays before and are now replacing them with tables. And if you have an application where that does not make sense, I'd love to hear about that as well. Let me know here.

Get
the MATLAB code

Published with MATLAB® R2017b

A=[1 2; 3 4] M = cat(3, A, A+1, A+2, A+3);

A = 1 2 3 4So the function should work like this:

IDX = [NaN 4; 3 2]

IDX = NaN 4 3 2

catdim = 3; szA = size(A); [mv,midx] = max(M >= 5,[],catdim); IDX = NaN(szA); IDX(mv) = midx(mv)

IDX = NaN 4 3 2Why/how did this work? Well, I use the condition I want met into function

A = randi(17, [3 2 1 3]); catdim = ndims(A)+1 M = cat(catdim, A, A+1, A+2, A+3, A+4);

catdim = 5See a slice of M

sliceOfM = M(:,:,:,1)

sliceOfM = 12 2 13 4 8 16Apply the

szA = size(A) [mv,midx] = max(M >= 13,[],catdim); IDX = NaN(szA); IDX(mv) = midx(mv)

szA = 3 2 1 3 IDX(:,:,1,1) = 2 NaN 1 NaN NaN 1 IDX(:,:,1,2) = NaN 1 1 NaN 4 NaN IDX(:,:,1,3) = NaN 1 1 1 NaN 1

I recently attended the annual AGU (American Geophysical Union) meeting and, used the time at our booth to talk to many geoscientists about many different topics. One that emerged as a big interest stemming from unfamiliarity is deep learning.... read more >>

]]>I recently attended the annual AGU (American Geophysical Union) meeting and, used the time at our booth to talk to many geoscientists about many different topics. One that emerged as a big interest stemming from unfamiliarity is deep learning.

At MathWorks we have been adding to our machine learning and deep learning repertoire ardently. One reflection of this is the newest blog, on deep learning, authored by Steve Eddins, also the author of the Steve on Image Processing blog.

Most applications of deep learning these days are focused on images, with signals coming along strongly now as well. Here's a link to some MATLAB examples/applications in more traditional areas like object detection.

In the sciences, successes have been reported in biological and medical studies.

In domains, such as geosciences, often data can be viewed as an image even if they don't represent an actual picture. We had several discussions at AGU about possible applications of deep learning for seismic problems, atmospheric ones, and oceanographic ones. And deep learning is certainly having some success in some remote sensing applications, from a quick web search.

Do you know of any people or applications currently using deep learning in their work? What domain? What do you see looking forward to the application of deep learning in domains you know most about? Let us know here.

Get
the MATLAB code

Published with MATLAB® R2017b

This is one time of the year when there is often an abundance of baked goods showing up in my office, and many others no doubt. And you hear people say things like, "That's the best cookie I ever had!". And sometimes a debate ensues.... read more >>

]]>This is one time of the year when there is often an abundance of baked goods showing up in my office, and many others no doubt. And you hear people say things like, "That's the best cookie I ever had!". And sometimes a debate ensues.

One problem, of course, is that not all cookies are good. Another is not all baked goods are cookies. Hmmm, there must be some math that could help us out here.

A colleague just pointed out a thread on Reddit where there is a discussion about cookies, and which ones are best. In an effort to resolve the intense debate, one employee analyzed recipes to determine which ones qualify as a cookie.

To do so, the author

- scraped recipes from the net, including ones including the term "cookie" and some other chosen terms,
- used the ingredient lists as input to principal component analysis to reduce the dimensionality of the problem,
- applied clustering algorithms and and support vector machines to distinguish between pastries and cookies

The conclusion reached - some very tasty tarts did not quality for best cookie! Do you use MATLAB recreationally? To learn new concepts that might not yet be relevant for your work, but you are curious about? We'd love to hear your ideas here.

Get
the MATLAB code

Published with MATLAB® R2017b

There are a lot of ways of sharing your ideas with MATLAB these days. Including... read more >>

]]>There are a lot of ways of sharing your ideas with MATLAB these days. Including

- MATLAB scripts and functions
- Live scripts
- MAT-files
- Apps
- Code generation of various kinds, e.g., C/C++ and GPU via Coder products
- MATLAB Compiler and SDK (stand-alone apps and code suitable for integrating into other environments)
- MATLAB Production Server

Today I want to remind you of some tools in MATLAB that can facilitate the transition to code you want to deploy via the MATLAB Compiler and SDK.

Here's a list of the functions I find most useful to aid in deployment.

Do you have other functions that ease your transition to deploying your app? Let me know here.

Get
the MATLAB code

Published with MATLAB® R2017b