Created
May 3, 2013 14:27
-
-
Save chris-taylor/5509428 to your computer and use it in GitHub Desktop.
Writes code that evaluates to a given Matlab object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function code = mcode(x) | |
% MCODE Returns a char array containing Matlab code that evaluates to the | |
% object x. That is, the two quantities | |
% | |
% >> x | |
% >> eval(mcode(x)) | |
% | |
% should be identical. | |
% | |
%Author: Chris Taylor | |
%Last modified: 3 May 2013 | |
switch class(x) | |
case {'double', 'single'} | |
code = arraycode(x, class(x), '%.20g'); | |
case {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'} | |
code = arraycode(x, class(x), '%d'); | |
case {'cell'} | |
code = cellcode(x); | |
case {'char'} | |
code = charcode(x); | |
case {'logical'} | |
code = ['logical(' arraycode(x, 'int8', '%d') ')']; | |
case {'struct'} | |
code = structcode(x); | |
case {'function_handle'} | |
code = evalc('disp(x)'); | |
code(1:4) = []; | |
end | |
function code = arraycode(x,cls,fmt) | |
[N,M] = size(x); | |
if isempty(x) | |
code = [cls '([])']; | |
elseif numel(x) == 1 | |
code = num2str(x,fmt); | |
else | |
code = '['; | |
for n = 1:N | |
for m = 1:M | |
code = [code num2str(x(n,m),fmt) ',']; %#ok | |
end | |
code = [code(1:end-1) ';']; | |
end | |
code = [code(1:end-1) ']']; | |
end | |
function code = cellcode(x) | |
[N,M] = size(x); | |
if isempty(x) | |
code = '{}'; | |
else | |
code = '{'; | |
for n = 1:N | |
for m = 1:M | |
code = [code util.mcode(x{n,m}) ',']; %#ok | |
end | |
code = [code(1:end-1) ';']; | |
end | |
code = [code(1:end-1) '}']; | |
end | |
function code = charcode(x) | |
N = size(x,1); | |
if isempty(x) | |
code = ''''''; | |
elseif N == 1 | |
code = ['''' x '''']; | |
else | |
code = '['; | |
for n = 1:N | |
code = [code '''' x(n,:) ''';']; %#ok | |
end | |
code = [code(1:end-1) ']']; | |
end | |
function code = structcode(x) | |
[N,M] = size(x); | |
if isempty(x) | |
code = 'struct([])'; | |
elseif numel(x) == 1 | |
fn = fieldnames(x); | |
code = 'struct('; | |
for ii = 1:length(fn) | |
code = [code '''' fn{ii} ''',' util.mcode(x.(fn{ii})) ',']; %#ok | |
end | |
code = [code(1:end-1) ')']; | |
else | |
code = '['; | |
for n = 1:N | |
for m = 1:M | |
code = [code structcode(x(n,m)) ',']; %#ok | |
end | |
code = [code(1:end-1) ';']; | |
end | |
code = [code(1:end-1) ']']; | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment