Michael
Michael

Reputation: 7809

Properly write into string in Matlab (efficient and preserving escape characters)

I have an abstract class Writer which allows clients to write into something. Could be the screen, could be a file. Now, I try to create a derived class to write into a string.

I have two problems with the denoted line in method write(...):

  1. It's probably very inefficient. Is there something like a string buffer in Matlab?
  2. It writes escape sequences like \n plain into the string, instead of taking their actual meaning.

How can I get the denoted line properly?

Code:

classdef StringTextWriter < Writer

properties
    str;
end

methods

    function this = StringTextWriter()
        % Init the write-target which is a string in our case.
        % (Other Writer classes would maybe open a file.)
        this.str = '';
    end

    function write(this, val)
        % Write to writer target.
        % (Other Writer classes would maybe use fprinf here for file write.)

        % ?????????????????????????????
        this.str = [this.str val]; % How to do this properly?
        % ?????????????????????????????
    end

end

end

Upvotes: 1

Views: 52

Answers (1)

user2271770
user2271770

Reputation:

To answer your questions point by point:

  1. The closest notion to a string buffer would be a string cell. Instead of:

    str = '';
    str = [strbuf, 'abc\n'];
    str = [strbuf, 'def\n'];
    str = [strbuf, 'ghi\n'];
    %// and so on...
    

    one may use

    strbuf = {};
    strbuf{end+1} = 'abc\n';
    strbuf{end+1} = 'def\n';
    strbuf{end+1} = 'ghi\n';
    %// and so on...
    str = sprintf([strbuf{:}]); %// careful about percent signs and single quotes in string
    

    the drawback being that you have to reconstruct the string every time you ask for it. This can be alleviated by setting a modified flag every time you add strings to the end of strbuf, resetting it every time you concatenate the strings, and memoizing the result of concatenation in the last line (rebuild if modified, or last result if not).

    Further improvement can be achieved by choosing a better strategy for growing the strbuf cell array; probably this would be effective if you have a lot of write method calls.

  2. The escape sequences are really linked to the <?>printf family and not to the string literals, so MATLAB in general doesn't care about them, but sprintf in particular might.

Upvotes: 2

Related Questions