Efficient String Concatenation in Matlab

Viewed 1702

A while ago I stumbled upon this document. It assess the performance of several concatenating methods in python. Here are the 4 out of the 6 methods that it compares:

Python String Concatenation Methods

Method 1: Naive appending

def method1():
    out_str = ''
    for num in xrange(loop_count):
        out_str += `num`
    return out_str

Method 4: Build a list of strings, then join it

def method4():
  str_list = []
  for num in xrange(loop_count):
    str_list.append(`num`)
  return ''.join(str_list)

Method 5: Write to a pseudo file

def method5():
    from cStringIO import StringIO
    file_str = StringIO()
    for num in xrange(loop_count):
        file_str.write(`num`)
    return file_str.getvalue()

Method 6: List comprehensions

def method6():
    return ''.join([`num` for num in xrange(loop_count)])

The conclusions from the results go as follows:

I would use Method 6 in most real programs. It's fast and it's easy to understand. It does require that you be able to write a single expression that returns each of the values to append. Sometimes that's just not convenient to do - for example when there are several different chunks of code that are generating output. In those cases you can pick between Method 4 and Method 5.

After reading this document I realized that I was not aware of methods 5 and 6. For the most part, I now prefer to use method 5 since it allows me to write to a string in the same way as I would to a file.

My question is the following, what are the different techniques in matlab for string concatenation? I hardly deal with strings in matlab but I have come up with a problem that requires me to write a string. One solution I was thinking of was to write to a temporary file and read the file once this is done. But before doing this I decided to ask and see if there are better options. For now here is a naive appending method in matlab:

Matlab String Concatenation Methods

Method 1: Naive appending

function out_str = method1(loop_count)
    out_str = '';
    for num=1:loop_count
       out_str = [out_str num2str(num)]; %#ok<AGROW>
    end
end

Are there similar methods in Matlab to method 4, 5, and 6 that we can use for efficiency comparison?

EDIT:

Here is some method similar to method 5 in python (writing to a file):

function out_str = method2(loop_count)
    fid = fopen('._tmpfile.tmp', 'w');
    for num=1:loop_count
        fprintf(fid, '%d', num);
    end
    fclose(fid);
    out_str = fileread('._tmpfile.tmp');
end

And this is a simple test:

>> tic; tmp1 = method1(100000); toc
Elapsed time is 13.144053 seconds.
>> tic; tmp2 = method2(100000); toc
Elapsed time is 2.358082 seconds.
2 Answers
Related