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

Lather, rinse and repeat

| categories: math | View Comments

recursive_functions

Contents

Lather, rinse and repeat

John Kitchin 5/28/2012

Recursive functions are functions that call themselves repeatedly until some exit condition is met. Today we look at a classic example of recursive function for computing a factorial. The factorial of a non-negative integer n is denoted n!, and is defined as the product of all positive integers less than or equal to n.

function main

recursive function definition

The key ideas in defining a recursive function is that there needs to be some logic to identify when to terminate the function. Then, you need logic that calls the function again, but with a smaller part of the problem. Here we recursively call the function with n-1 until it gets called with n=0. 0! is defined to be 1.

    function f = recursive_factorial(n)
        % compute the factorial recursively. Note if you put a negative
        % number in, this function will never end. We also do not check if
        % n is an integer.
        if n == 0
            % this is the terminating case
            f = 1
        else
            % otherwise we call the function again, this time with n-1
            f = n * recursive_factorial(n-1)
        end
    end
f =

     1


f =

     1


f =

     2


f =

     6


f =

    24


f =

   120


ans =

   120

Matlab factorial function

factorial(5)
ans =

   120

Now our function

recursive_factorial(5)

Compare to a loop solution

This example can also be solved by a loop. This loop is easier to read and understand than the recursive function. Note the recursive nature of defining the variable as itself times a number.

n = 5;
factorial_loop = 1;
for i=1:n
    factorial_loop = factorial_loop*i
end
factorial_loop =

     1


factorial_loop =

     2


factorial_loop =

     6


factorial_loop =

    24


factorial_loop =

   120

Conclusions

Recursive functions have a special niche in mathematical programming. There is often another way to accomplish the same goal. That isn't always true though, and in a future post we will examine cases where recursion is the only way to solve a problem.

end

% categories: math
% 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

Issues with nested functions

| categories: uncategorized | View Comments

nested_function_issues

Contents

Issues with nested functions

John Kitchin

Nested functions are great for passing lots of information between functions conveniently. But, there are some gotchas to be wary of!

function main

a typical nested function use

It is common to define several parameters, and then to use them inside a nested function

a = 4;
b = 3;

    function y = f1(x)
        y = a + b*x;
    end

f1(2)
ans =

    10

classic example of a potential problem

Nested functions share the same namespace as the main function, which means you can change the value of a variable in the main function in the nested function. This does not happen with subfunctions.

i = 5 % initial value of i
    function y = f2(x)
        % nested function that uses a and b from above, and uses an
        % internal loop to compute a value of y.
        y = 0;
        for i=1:10  % this is going to change the value of i outside this function
            y = y + a*b + i;
        end
    end

f2(2)
i % note i = 10 now
i =

     5


ans =

   175


i =

    10

This kind of behavior can be very difficult to debug or even know is a problem! you have to be aware that it is an issue when using nested functions.

subfunctions

subfunctions do not share namespaces, so you can reuse variable names. This can prevent accidental variable value changes, but, you have to put the variable information into the subfunction

i = 5
f3(2)
i % note that the value of i has not been changed here.
i =

     5


ans =

   175


i =

     5

end

function y = f3(x)
% subfunction that uses a and b from above, and uses an internal loop
% to compute a value of y.
a = 4;
b = 3;
y = 0;
for i=1:10  % this is going to change the value of i outside this function
    y = y + a*b + i;
end
end

% categories: basic
Read and Post Comments

« Previous Page -- Next Page »