Last post for a while

| categories: miscellaneous | View Comments

You may have noticed the site looks different from the last time you were here. The old Wordpress site was getting spammed heavily, so I have transferred the content to this static site. Hopefully all the links, paths, etc... are still the same. Let me know if you find broken links or missing content. This site has been viewed over 85,000 times since I put it up, so I am leaving the content up for those using it.

You can see it has been almost a year since the last post. This is the last post on this site for the forseeable future. I have switched to using Python for engineering and scientific calculations. You can find similar content as this site but in Python at http://jkitchin.github.io.

Read and Post Comments

what_do_you_want.m

| categories: miscellaneous | View Comments

 

What would you like to see on the Matlab blog?

Hi everyone! We recently passed the 100-post mark on the blog! What would you like to see as future blog posts? Leave a comment here!
% categories: miscellaneous
 
Read and Post Comments

Some of this, sum of that

| categories: miscellaneous | View Comments

recursive_sum

Contents

Some of this, sum of that

John Kitchin 5/29/2012

Matlab provides a sum function to compute the sum of a vector. However, the sum function does not work on a cell array of numbers, and it certainly does not work on nested cell arrays. We will solve this problem with recursion.

function main

Basic sum of a vector

v = [1 2 3 4 5 6 7 8 9]
sum(v)
v =

     1     2     3     4     5     6     7     8     9


ans =

    45

sum does not work for a cell

v = {1 2 3 4 5 6 7 8 9}  % note {} is a cell array
try
    sum(v)
catch
    'An error was caught!'
end
v = 

    [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]    [9]


ans =

An error was caught!

Compute sum of a cell array with a loop

In this case, it is not hard to write a loop that computes the sum. Note how the indexing is done. v{i} is the contents of the ith element in the cell array. v(i) is a new cell array containing the contents of the ith element.

s = 0;
for i=1:length(v)
    s = s + v{i};
end
sprintf('The sum of the cell array v = %d', s)
ans =

The sum of the cell array v = 45

Nested cell arrays

Suppose now we have nested cell arrays. This kind of structured data might come up if you had grouped several things together. For example, suppose we have 5 departments, with 1, 5, 15, 7 and 17 people in them, and in each department they are divided into groups.

Department 1: 1 person
Department 2: group of 2 and group of 3
Department 3: group of 4 and 11, with a subgroups of 5 and 6 making
              up the group of 11.
Department 4: 7 people
Department 5: one group of 8 and one group of 9.

We can represent that data as nested cell arrays like this.

v = {1,
    {2,3}
    {4,{5,6}},
    7,
    {8,9}}
v = 

    [       1]
    {1x2 cell}
    {1x2 cell}
    [       7]
    {1x2 cell}

Sum of nested cell arrays

Now, say we want to know the sum of the people in all departments. We can not write a loop to do this because of the nesting. Lets see what a loop would do.

for i=1:length(v)
    v{i}, class(v{i})
end
ans =

     1


ans =

double


ans = 

    [2]    [3]


ans =

cell


ans = 

    [4]    {1x2 cell}


ans =

cell


ans =

     7


ans =

double


ans = 

    [8]    [9]


ans =

cell

You can see the output of v{i} is variable. Sometimes it is a number, sometimes it is a new cell array, and sometimes a new nested cell array. There is no set of loops we can construct to add all the numbers. Instead, we have to construct a recursive function that goes into each nested cell array to the end, gets the numbers and adds them up.

a recursive sum function

For a recursive function we need to identify the situation that is terminal, work towards the terminal condition, and then call the function again. Here, as we traverse the cell array, when we get a number we end the recursive call, and when we get another cell array we recurse. So, we will iterate over the cell array, and everytime we find a number we add it to the sum, and otherwise call the function again

    function s = recursive_sum(v)
        % v is a (possibly nested) cell array
        s=0; % initial value of sum
        for i=1:length(v)
            if isnumeric(v{i})
                % this is the terminal step
                v{i}  % show the order of traversal
                s = s + v{i};
            else
                % we got another cell, so we recurse
                s = s + recursive_sum(v{i});
            end
        end
    end

Test the recursive function

We should get the same answer as before. and we do. You can also see that the numbers are added up in the order you go through the cell array.

recursive_sum(v)
ans =

     1


ans =

     2


ans =

     3


ans =

     4


ans =

     5


ans =

     6


ans =

     7


ans =

     8


ans =

     9


ans =

    45

check on a non-nested cell array

recursive_sum({1,2,3,4,5,6,7,8,9})
ans =

     1


ans =

     2


ans =

     3


ans =

     4


ans =

     5


ans =

     6


ans =

     7


ans =

     8


ans =

     9


ans =

    45

check on a non-cell array argument

try
    recursive_sum([1,2,3,4,5,6,7,8,9])
catch
    disp('our function does not work if the argument is not a cell array!')
end
our function does not work if the argument is not a cell array!

Conclusions

In Post 1970 we examined recursive functions that could be replaced by loops. Here we examine a function that can only work with recursion because the nature of the nested data structure is arbitrary. There are arbitary branches and depth in the data structure. Recursion is nice because you don't have to define that structure in advance.

end

% categories: Miscellaneous
% tags: recursive
Read and Post Comments

Enhancements to Matlab wordpress

| categories: miscellaneous | View Comments

Enhancements to Matlab wordpress

Enhancements to Matlab wordpress

John Kitchin May 7, 2012

I modified some of my wordpress matlab code to make some enhancements in the publishing process. Mostly I wanted some markup to make the blog posts a little nicer. For example, a markup to indicate a command, or to make sure a file can be downloaded, and to make tooltips on text.

Contents

a better command markup

I wanted command references in the posts to have a link to some documentation of the command. there doesn't seem to be a systematic way to get the url to Matlab documentation, so I settled for a search on Matlab's site. See: fsolve command! Click on the link to search Matlab's website for it. All that from:

:command:`fsolve`

Download links

sometimes examples need a file to work. you can download test.m

:download:`test.m`

tooltips

. Here is the markup for a tooltip. At publish time I add a little javascript to the html to make this happen.

:tooltip:`<Surprise! you just found a tooltip!> Hover on me!`

Random plot

I have to upload the graphics to wordpress, then change the url in the img src attribute.

plot(1:5,5:9)

Warnings

Sometimes warning text should be obvious!


WARNING: Something can fail badly if you do that.

Notes

I also like to separate out notes about some things.
Note: You can also try this variation!

where is the code?

You can see the code at https://github.com/johnkitchin/matlab-wordpress.

% categories: miscellaneous
% tags: blog, publish


% post_id = 1937; %delete this line to force new post;
% permaLink = http://matlab.cheme.cmu.edu/2012/05/08/enhancements-to-matlab-wordpress-2/;
Read and Post Comments

Brief intro to regular expressions

| categories: miscellaneous | View Comments

intro_regexp

Contents

Brief intro to regular expressions

John Kitchin 5/6/2012

This example shows how to use a regular expression to find strings matching the pattern :cmd:`datastring`. We want to find these strings, and then replace them with something that depends on what cmd is, and what datastring is.

function main
clear all;

    function html = cmd(datastring)
        % replace :cmd:`datastring` with html code with light gray
        % background
        s = '<FONT style="BACKGROUND-COLOR: LightGray">%s</FONT>';
        html = sprintf(s,datastring);
    end

    function html = red(datastring)
        % replace :red:`datastring` with html code to make datastring
        % in red font
        html = sprintf('<font color=red>%s</font>',datastring)
    end

Define a multiline string

text = ['Here is some text. use the :cmd:`open` to get the text into\n'...
    ' a variable. It might also be possible to get a multiline :red:`line\n' ...
    ' one line 2` directive.'];
sprintf(text)
ans =

Here is some text. use the :cmd:`open` to get the text into
 a variable. It might also be possible to get a multiline :red:`line
 one line 2` directive.

find all instances of :*:`*`

regular expressions are hard. there are whole books on them. The point of this post is to alert you to the possibilities. I will break this regexp down as follows. 1. we want everything between :*: as the directive. ([^:]*) matches everything not a :. :([^:]*): matches the stuff between two :. 2. then we want everything between `*`. ([^`]*) matches everything not a `. 3. The () makes a group that matlab stores as a token, so we can refer to the found results later.

regex = ':([^:]*):`([^`]*)`';
[tokens matches] = regexp(text,regex, 'tokens','match');

for i = 1:length(tokens)
    directive = tokens{i}{1};
    datastring = tokens{i}{2};
    sprintf('directive = %s', directive)
    sprintf('datastring = %s', datastring)

    % construct string of command to evaluate directive(datastring)
    runcmd = sprintf('%s(''%s'')', directive, datastring)
    html = eval(runcmd)

    % now replace the matched text with the html output
    text = strrep(text, matches{i}, html);
    % now
end
ans =

directive = cmd


ans =

datastring = open


runcmd =

cmd('open')


html =

<FONT style="BACKGROUND-COLOR: LightGray">open</FONT>


ans =

directive = red


ans =

datastring = line\n one line 2


runcmd =

red('line\n one line 2')


html =

<font color=red>line\n one line 2</font>


html =

<font color=red>line\n one line 2</font>

See modified text

sprintf(text)
ans =

Here is some text. use the <FONT style="BACKGROUND-COLOR: LightGray">open</FONT> to get the text into
 a variable. It might also be possible to get a multiline <font color=red>line
 one line 2</font> directive.

this shows the actual html, rendered to show the changes.

web(sprintf('text://%s', text))
end

% categories: miscellaneous
% tags: regular expression

% post_id = 1701; %delete this line to force new post;
% permaLink = http://matlab.cheme.cmu.edu/2012/05/07/1701/;
Read and Post Comments

Next Page »