Code covered by the BSD License

# Simscape Language Equations, Pretty Print

### Jean-Baptiste Lanfrey (view profile)

14 Jan 2011 (Updated )

MATLAB code for displaying Simscape language equations in a format that is easy to read.

replacePattern.m
```function eqs = replacePattern(eqs,pat,ignoreBackslash,rev,reppat,switchstr)
% Copyright 2011 The MathWorks, Inc.

if nargin < 3
ignoreBackslash = 0;
rev = 1;
reppat = '';
switchstr = 0;
elseif nargin < 4
rev = 1;
reppat = '';
switchstr = 0;
elseif nargin < 5
reppat = '';
switchstr = 0;
elseif nargin < 6
reppat = '';
switchstr = 0;
end

lenghtPat = numel(pat)-ignoreBackslash;

%Read equation from end to beginning if rev == 2
if rev == 2
eqs = eqs(end:-1:1);
end

repStr = ['(',')','{','}';
')','(','}','{'];

% curly brace: pattern is followed by '{'
pattern = ['(' pat ')([\' repStr(rev,3) '][\w\-\.\(\)\{\}\/\+\*\\\^\;]+)'];
[buf1,buf2,buf3,buf4,e]=regexp(eqs,pattern);
eqs = addDelimAroundEq(eqs,repStr(rev,3),repStr(rev,4),'\$',''); %avoid infinite loop
% replace \$ by repStr(rev,3)
eqs = strrep(eqs,'\$',repStr(rev,3));
% replace  by repStr(rev,4)
eqs = strrep(eqs,'',repStr(rev,4));

% parenthesis: pattern is followed by '('
pattern = ['(' pat ')([\' repStr(rev,1) '][\w\-\.\(\)\{\}\/\+\*\\\^\;]+)'];
[buf1,buf2,buf3,buf4,e]=regexp(eqs,pattern);

% pattern is NOT followed by '(' or '{'
pattern = ['(' pat ')([^\(|^\)|^\{|^\}|-?]?[0-9a-zA-Z\_\.\^]+)'];
if switchstr == 0
eqs = regexprep(eqs,pattern,['\$1' repStr(rev,3) '\$2' repStr(rev,4)]);
else
eqs = regexprep(eqs,pattern,[repStr(rev,3) '\$2' repStr(rev,4) reppat(end:-1:1)]);
end

function eqs = addDelimAroundEq(eqs, leftDelim, rightDelim, leftDelimRep, rightDelimRep)
while ~isempty(e)
[buf1,buf2,buf3,buf4,e]=regexp(eqs,pattern);

for j = 1:numel(e)
str=cell2mat(e{j}(2));
a=regexp(eqs,pattern);

count = 1;
kk=1;
for k=2:numel(str)
kk=kk+1;
if strcmp(str(kk),leftDelim)
count = count + 1;
elseif strcmp(str(kk),rightDelim)
count = count - 1;
end
if count == 0
if kk<numel(str)
if ~strcmp(str(kk+1),'^')
break
else
kk=kk+1;
end
end
end
end

if switchstr == 0
eqs = [eqs(1:a+lenghtPat-1) leftDelimRep eqs(a+lenghtPat:a+lenghtPat-1+kk) rightDelimRep eqs(a+lenghtPat+kk:end)];
else
eqs = [eqs(1:a-1) leftDelimRep eqs(a+lenghtPat+1:a+lenghtPat-1+kk-1) rightDelimRep reppat(end:-1:1) eqs(a+lenghtPat+kk:end)];
end
end
end
end

if rev == 2
eqs = eqs(end:-1:1);
end

end
```