Advertisement
Guest User

fig2texPS

a guest
Oct 21st, 2011
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 142.96 KB | None | 0 0
  1. %% |fig2texPS| - Export Matlab Figure to LaTeX
  2. %  Last Modification
  3. %  Date:    21.10.2011
  4. %  Author:  Adin Ramirez
  5. %  Version: 0.5.4
  6. %
  7. % Original Author:  Peter Scholz (03.11.2010)
  8. % Email:   contact@peter-scholz.net
  9. %
  10. % This MATLAB function converts a figure to a LaTeX file with PSTricks
  11. % compatible macros. The packages |pstricks|, |pst-node|, |pst-plot|,
  12. % |pst-circ| and |moredefs| are required. A minimal example latex code is
  13. % generated at each time this script is run. The tex file can also be a
  14. % stand-alone file so that the paper size matches the figure outline.
  15.  
  16. %% Motivation
  17. %
  18. % The conversion tool has been written for the following reasons (compared
  19. % to eps with psfrag):
  20. %
  21. % * With |eps with psfrag| it is cumbersome to replace all tick labels
  22. % * When replacing text in a legend with |eps with psfrag|, the size of the
  23. % legend's box is NOT
  24. % adapted -> this is different in this tool because PSTricks macros are
  25. % used and the box size is adapted to its content
  26. % * When resizing an |eps|-Figure, the widths of all lines are scaled as
  27. % well -> With this tool, all linewidths are equal independent on the size of
  28. % the figure. This guarantees a neat appearance in documents with many
  29. % different figures
  30. % * |eps|-Figures, created by Matlab have a surrounding box that may be
  31. % unwanted sometimes, especially in two-column documents. -> Here, the box
  32. % size can be chosen to be either minimal or fixed
  33. % * The output of this tool is a tex file that is easy to read. For
  34. % instance, each grid line is one line in the TeX document. This offers
  35. % the possibility to finetune the figure with any of the powerful PSTricks
  36. % macros
  37.  
  38. %% Properties
  39. % The aim of this function is to create a tex-code picture of a Matlab
  40. % figure in PSTricks syntax that can still be adapted after creation.
  41. %
  42. % *Supported Features:*
  43. %
  44. % * 2D plots with arbitrary number of lines and patches
  45. % * Linear and logarithmic axes and second y-axis
  46. % * Grids, subgrids, ticks and subticks
  47. % * Arbitrary colors, linestyles and markers
  48. % * Labels, title, legend and colorbar
  49. % * Annotations (TextArrows and TextBoxes) are supported
  50. % * GUI, where the fontsize, plotsize and the export file location can be
  51. % set
  52. % * Lines with many datapoints can be compressed in order to reduce file
  53. % size and compilation time (copied from |Matfig2PGF| by Paul Wagenaars in
  54. % 2008)
  55. % * Convergence Triangles can be shown for logarithmic plots
  56. % * Support of additional code in PSTricks syntax
  57. %
  58. % *Changes to Version 0.52 from 10.06.2010:*
  59. %
  60. % * small bugfixes
  61. % * dataplot -> psline replaced, option linejoin=1 introduced
  62. % * marker more bold
  63. % * fixed a bug for vertical lines that produced NaN values when cut
  64. % * enhancement for patches which are cut at the axes limits
  65. % * Colorbar enhancement, if the tight inset of the right side is larger,
  66. % this value is used instead
  67. % * fixed a bug for axes without tick labels
  68. %
  69. % *NOT Supported in this version:*
  70. %
  71. % * 3D Plots or contour plots
  72. % * Subfigures (if a figure with multiple axes is chosen, a dialog box
  73. % appears that allows to activate a certain axes)
  74. % * Other annotations than TextArrows, and TextBoxes
  75. % * Reverse Axes
  76. %
  77. % The matlab code is based on the
  78. % |<http://www.mathworks.de/matlabcentral/fileexchange/7884 fig2tex>|
  79. % file by Ercan Solak in 2005.
  80. % The key modifications are that the ratios can be set, implementation of
  81. % grids and logarithmic scale. The algorithm to reduce the number of large
  82. % data sets is copied from
  83. % |<http://www.mathworks.com/matlabcentral/fileexchange/12962 Matfig2PGF>|
  84. % by Paul Wagenaars in 2008.
  85. % Bertrand Scherrer added the support of textboxes on 09.06.2010
  86.  
  87. %% Bugs and ToDo's
  88. %
  89. % * 26.02.09: The annotations (TextArrows) are not shown in the visualized
  90. % figure, this has to be implemented
  91. % * 20.05.10: If patches are cut, the algorithm works in principle but the
  92. % patches are divided into multiple patches according to the algorithm used
  93. % for lines. This is wrong, instead a merging must be enforced in order to
  94. % draw a straight line at the border...
  95. % * 29.06.10: Bug if a legend is added for patches
  96.  
  97. %% Syntax
  98. %  fig2texPS()
  99. %  fig2texPS(fignum)
  100. %  fig2texPS(fignum,fname)
  101. %  fig2texPS(fignum,globals)
  102.  
  103. %% Description
  104. % *|fig2texPS()|* exports either the activated figure (|gcf|) or a test
  105. % function, if no figure is present.
  106. %
  107. % *|fig2texPS(fignum)|* exports the figure with the number |fignum|.
  108. %
  109. % *|fig2texPS(fignum,fname)|* exports the figure with the number |fignum|
  110. % and sets its name to |fname|. The name can be changed in the
  111. % Figure Export Properties later on.
  112. %
  113. % *|fig2texPS(fignum,globals)|* exports the figure with the number
  114. % |fignum|. The struct |globals| can be used in order to set different
  115. % settings from outside this function. See the fieldnames for further
  116. % explanation.
  117.  
  118. %% Figure Export Properties
  119. % <<GUI_settings.png>>
  120. %
  121. % The _Figure Export Properties_ GUI is opened together with a replot of the
  122. % figure for finetuning the export behavior. Each time a paramter is
  123. % changed, the replot is updated automatically. The GUI can be used to set
  124. % the following paramters:
  125. %
  126. % * *Width / cm* The width of either the figure or the axes can be set in
  127. % centimeters. This parameter can be changed in the tex-file as well. This
  128. % feature allows all figures in a
  129. % document to have the same size and style.
  130. % * *Figure or Axes* This checkbox allows to set if the chosen width
  131. % belongs to the axes or the total figure, in case of Figure, the size of
  132. % the axes is chosen automatically, in case of Axes the space for all
  133. % 'outer' text is added.
  134. % * *Height / Width* The height of the axes can be set by the height factor
  135. % relatively to the axes width. This allows for using the same aspect
  136. % ratios of all figures in a latex document.
  137. % * *Axis equal* Alternatively, the height can be set in such a way that
  138. % the data of the x-axis and the y-axis are in the same aspect ratio.
  139. % * *Square* In Addition, the height can be set in such a way being equal
  140. % to the width.
  141. % * *Auto Slider* This slider allows to adjust the surrounding space by
  142. % increasing or decreasing the size of the figure's text. Note, that the
  143. % fontsize has NO influence on the fontsize in the LaTeX document.
  144. % * *Center axes horizontally* Here it can be decided whether the axes should be
  145. % centered horizontally or not. If set, extra space is added either left or
  146. % right of the axes in order to keep the axes centered.
  147. % * *Manual Space Setting* The four fields *Left*, *Bottom*, *Right* and
  148. % *Top* allow to set the surrounding space manually. This is important,
  149. % when using subfigures in the TeX document. Hereby, it is guaranteed that
  150. % all figures are aligned correctly.
  151. % * *Draw figure outline* If activated, a box is plotted around the latex figure
  152. % in order to visualize the real figure size. If deactivated, no box is
  153. % drawn. However, the box can still be activated in the tex-file by
  154. % uncommenting the coresponding line.
  155. % * *Stand-alone file* If activated, a stand-alone tex-file is created that
  156. % can be compiled with dvi -> ps -> pdf. The borders are matched with the
  157. % size of the figure. Using this method, a pdf file can be generated that
  158. % can be used later on for pdftex documents.
  159. % * *Reduce data points* The number of data points can be reduced for lines
  160. % without any markers if this radiobutton is enabled. The reduction factor
  161. % can be set. If the factor gets smaller, the reduction becomes less. A
  162. % zero factor equals no reduction.
  163. % * *Legend style* The style of the legend can be set. Currently, a
  164. % rectangular box, a box with rounded corners, a shadowbox and no box are
  165. % supported.
  166. % * *Export to file* The filename can be set or changed.
  167.  
  168.  
  169. %% Example file
  170. % The following example picture shows the functionality of the script:
  171. %
  172. % <<fig2texPS_example.png>>
  173.  
  174.  
  175. function fig2texPS(varargin)
  176.  
  177. EPS=1e-10;
  178. s = warning('query', 'all'); % save warnings
  179. warning('off','all'); % disable all warnings
  180. % clc % clear screen
  181. %%
  182.  
  183. % INITIALIZATION
  184.  
  185. % create new struct 'globals' that contains all plot settings with the
  186. % following fields:
  187. globals = struct ( ...
  188.     'ShowGUI',              1, ...      % determine, whether the GUI is displayed or not
  189.     'BoundingBox',          0, ...      % draw a figure outline box for test aspects
  190.     'plotwidth',            10, ...     % width in cemtimeters (Originally: 10)
  191.     'widthType',            'axes', ... % alternatives: 'figure', 'axes'. When specifying figure,
  192.     ...                                 % a fixed surrounding (tightInset_cm) is not supported
  193.     'labelsep',             10, ...     % separation of labels
  194.     'labelsepMin',          8, ...      % minimum Label separation
  195.     'labelsepMax',          20, ...     % maximum Label separation
  196.     'AxesLineWidth',        0.5, ...    % in pt
  197.     'AxesBoxEnd',           0, ...      % if 1, the axes box will be drawn at the end and may overlay curves,
  198.     ...                                 % if 0, the axes box will be drawn before the content
  199.     'TextArrowLineWidth',   0.5, ...    % in pt
  200.     'TextArrowTextColor',   0, ...      % if 1, the color of the text will be same as the arrow,
  201.     ...                                 % if 0, the color of the text will be black
  202.     'TextBoxLineWidth',     0.5, ...    % in pt
  203.     'TextBoxTextColor',     0, ...      % if 1, the color of the text will be same as the box,
  204.     ...                                 % if 0, the color of the text will be black
  205.     'GridGreyFac',          0.8, ...    % grey factor of grid line color (0 ... black, 1 ... white)
  206.     'GridLineWidth',        0.4, ...    % in pt
  207.     'GridLineDotSep',       0.4, ...    % in pt
  208.     'MinorGridLineWidth',   0.4, ...    % in pt
  209.     'MinorGridLineDotSep',  0.8, ...    % in pt
  210.     'TickMajorLengthRel',   0.012, ...  % relative to x-length
  211.     'TickMinorLengthRel',   0.008, ...
  212.     'MarkerSize',           4, ...      % in pt
  213.     'LineWidth',            0.7, ...    % in pt
  214.     'EdgeLineWidth',        0.4, ...    % in pt (linewidth of the edges of the patches)
  215.     'FontSizeXYlabel',      '\small', ... % size of the xlabel, ylabel and title, may be any
  216.     ...                                 % LaTeX compatibel size like \tiny \small etc.
  217.     'FontSizeTickLabels',   '\footnotesize', ... % size of all labels
  218.     'FontSizeLegend',       '\footnotesize', ...
  219.     'FontSizeAnnotations',  '\small', ...
  220.     'FloatingPointFormat',  '%6.6f', ...
  221.     'PointReduceFactor',    0.0001, ... % factor that determines the reducing of the plot points
  222.     'idx_LegendStyle',      3, ...      % 1:    'Rectangular Box'
  223.     ...                                 % 2:    'Rounded corners'
  224.     ...                                 % 3:    'Shadowbox'
  225.     ...                                 % 4:    'No Box'
  226.     'LegendOffsetFac',      2, ...      % Factor relative to the TickMajorLength for the offset of the Legend Box
  227.     'heightFactor',         [], ...     % factor between axes width and height. If
  228.     ...                                 % empty [], ratio is set automatically,
  229.     ...                                 % e.g. 0.7 means that the height has 70 % of the width
  230.     'centerAxes',           0, ...      % if 1, extra space is addd to the right side of the axes in order to center the figure
  231.     'tightInset_cm',        [], ...     % The extra space between the axes and the figure borders can be set in cm
  232.     ...                                 % [left bottom right top] in cm or leave empty []
  233.     ...                                 % the width must be the width of the axes
  234.     'ColorBarWidth_cm',     [0.6, 0.3], ...     % Either empty (auto size), scalar (width) or 1x2 vector (width, offset)
  235.     'pathname',             pwd, ...
  236.     'filename',             'fig1.tex', ... % test tex-file name
  237.     'StandAloneFile',       0 ...      % if set to 1, a standalone file is generated that can be used to create a pdf file
  238.     );
  239.  
  240. % Optional Convergence Triangle Settings:
  241. globals.TriangleOrder = []; % vector with orders that are shown, if empty, no convergence triangle
  242. globals.TriangleColor = [0.4 0.4 0.4]; % rgb vector
  243. globals.TriangleLxRel = 0.3;
  244. globals.TriangleStr   = {};
  245.  
  246. globals.AddCode = {}; % additional code before '\end{pspicture}'
  247.  
  248.  
  249. %%
  250.  
  251. % EVALUATE INPUT ARGUMENTS
  252. numInputs=size(varargin,2); % number of input elements
  253. if numInputs==0,        % test case without any inputs
  254.     globals.StandAloneFile = 1; % do it in standalone for zero inputs
  255.     % test if there is at least one figure open
  256.     if isempty(get(0,'CurrentFigure')), % case where no figure is open, create test figure
  257.         fignum=figure; % create new figure and set fignum to this figure
  258.         time=linspace(0,40,500); % create time vector
  259.         Z1=exp(-0.1*time).*sin(time);
  260.         Z2=exp(-0.1*time);
  261.         Z3=-exp(-0.1*time);
  262.         plot(time,Z1,'-b','Linewidth',2);
  263.         hold on; grid on;
  264.         plot(time,Z2,'--r','Linewidth',2);
  265.         plot(time,Z3,'--r','Linewidth',2);
  266.         set(gca,'YLim',[-1,1]);
  267.         xlabel('Time $t$','interpreter','none')
  268.         ylabel('Magnitude','interpreter','none')
  269.         title('This is a test figure created by fig2texPS','interpreter','none')
  270.         legend({'$e^{-0.1 t}\cdot\sin(t)$','$\pm\,e^{-0.1 t}$'},'Location','NorthEast','interpreter','none')
  271.         annotation(gcf,'textarrow',[0.4625 0.367857142857143],...
  272.             [0.706142857142857 0.642857142857143],'TextEdgeColor','none',...
  273.             'String',{'Envelope'});
  274.     else
  275.         fignum=figure(gcf); % choose current figure
  276.     end
  277.    
  278. elseif numInputs==1,    % figure number is given
  279.     fignum=varargin{1};   % copy first input argument to fignum
  280.    
  281. elseif numInputs==2,    % figure number and filename are given
  282.     fignum = varargin{1};   % copy first input argument to fignum
  283.    
  284.     if isstruct (varargin{2}) % option |fig2texPS(fignum,globals)|
  285.         glob_cp = varargin{2};
  286.         names = fieldnames (glob_cp);
  287.         for ii = 1 : length (names),
  288.             globals = setfield (globals, names{ii}, getfield (glob_cp, names{ii}));
  289.         end
  290.        
  291.     else
  292.         fname  = varargin{2};   % copy second input argument to fname
  293.         [pathstr, name, ~] = fileparts(fname);
  294.         if ~isempty(pathstr),
  295.             globals.pathname = pathstr;
  296.         end
  297.         globals.filename = strcat(strrep(name,'.tex',''),'.tex'); % append .tex if not already there
  298.        
  299.     end
  300.    
  301.    
  302. else
  303.     h=warndlg('Wrong input setup!','Warning!','modal');
  304.     uiwait(h);
  305.     warning(s); % turn on specified warnings again
  306.     return
  307. end
  308.  
  309. % test if this figure exists
  310. fig_nums=get(0,'Children');
  311. if isempty(find(fig_nums==fignum))
  312.     h=warndlg('The chosen figure does not exist!','Warning!','modal');
  313.     uiwait(h);
  314.     warning(s); % turn on specified warnings again
  315.     return
  316. end
  317.  
  318. figure(fignum); % activate the right figure
  319. fh = gcf; % figure handle
  320. set(fh,'WindowStyle','normal')
  321.  
  322. % get the number and order of axes (subfigures)
  323. childs=get(fh,'children'); % all axes and legends, but wrong order and doubled
  324. subAxes=[]; % init
  325. for ii=1:length(childs), % scan all childs and search for legends
  326.     if strcmp(get(childs(ii),'type'),'legend') || strcmp(get(childs(ii),'type'),'axes')
  327.         legh = legend(childs(ii));
  328.         if isempty(legh) || childs(ii)~=legh, % new axes found
  329.             subAxes=[subAxes, childs(ii)];
  330.         end
  331.     end
  332. end
  333. subAxes=fliplr(subAxes); % extract subaxes by flipping them
  334. numAxes=length(subAxes);
  335. if numAxes==0, % no axis, cancel
  336.     warndlg('No Axes found!')
  337.     warning(s); % turn on specified warnings again
  338.     return
  339. end
  340. ahSecond = []; % init
  341. ColBar   = [];
  342. if numAxes==1, % only one axes, take it
  343.     ah=subAxes(1);
  344. else % multiple axes found
  345.     % check if two axes belong together (second y-axis)
  346.     pos_last=[0 0 0 0]; % init
  347.     numSubplots=0; % init
  348.     for ii=1:numAxes,
  349.        
  350.         % test for colorbars
  351.         if strcmp(get(subAxes(ii),'Tag'), 'Colorbar')            
  352.            
  353.             % save colorbar for later usage and do not treat as a normal
  354.             % axes
  355.             ColBar = get(subAxes(ii));          
  356.             ColBar.cmap = colormap; % get the corresponding colormap
  357.            
  358.         else
  359.            
  360.             set(subAxes(ii),'Units','normalized');
  361.             pos_act=get(subAxes(ii),'Position');
  362.             if norm(pos_act-pos_last)<EPS, % second axes found
  363.                 disp('Found two axes that belong together')
  364.                 AxesIndxTot(ii)=ii-1;
  365.             elseif strcmp(get(subAxes(ii),'YAxisLocation'),'right') % axes with right y-axis location
  366.                 disp('Found axes with right y-axis that has nonmatching size. Converting size ...')
  367.                 %             set(subAxes(ii),'Position',pos_last);
  368.                 AxesIndxTot(ii)=ii-1;
  369.             else
  370.                 numSubplots=numSubplots+1;
  371.                 % extract y-label as titles for the subfigures
  372.                 Strs{numSubplots}=get(get(subAxes(ii),'YLabel'),'String');
  373.                 if isempty(Strs{numSubplots}) % no ylabel
  374.                     Strs{numSubplots}=['Axis ',num2str(numSubplots)]; % generate one
  375.                 end
  376.                 AxesIndxTot(ii)=ii;
  377.                 AxesIndx(numSubplots)=ii;
  378.             end
  379.             pos_last=pos_act; % update
  380.            
  381.         end
  382.     end
  383.     if numSubplots>1, % choose
  384.         [selectionNumber,ok] = listdlg('PromptString','Choose Axis:','ListSize',[160 160],...
  385.             'SelectionMode','single',...
  386.             'ListString',Strs);
  387.     else
  388.         selectionNumber=1; ok=1;
  389.     end
  390.     if not(ok),
  391.         warning(s); % turn on specified warnings again
  392.         return,
  393.     else
  394.         ah=subAxes(AxesIndx(selectionNumber)); % take chosen axis
  395.         idx=find(AxesIndxTot==AxesIndx(selectionNumber));
  396.         if length(idx)==2; % copy second axes
  397.             ahSecond=subAxes(idx(end));
  398.         end
  399.     end
  400. end
  401.  
  402. % create empty string cell array in order to rearrange lines later on
  403. StrFile={};
  404.  
  405.  
  406.  
  407.  
  408.  
  409. %%
  410.  
  411. % EXTRACT ALL IMPORTANT FIGURE DATA
  412.  
  413. % Test if one or more axes have reverse style -> warning
  414. if strcmp(get(ah,'XDir'),'reverse') || strcmp(get(ah,'YDir'),'reverse') ...
  415.         || strcmp(get(ahSecond,'YDir'),'reverse')
  416.     h=warndlg('At least one axis is reversed! This is currently not supported. If you are using the spy-command, simply flipud(A) and change the labels manually.','Warning!','modal');
  417.     uiwait(h);
  418. end
  419.  
  420. % Test if Scales are log
  421. if strcmp(get(ah,'XScale'),'log'), fig.xLog=1; else fig.xLog=0; end
  422. if strcmp(get(ah,'YScale'),'log'), fig.yLog=1; else fig.yLog=0; end
  423.  
  424. % Test if axes are visible
  425. if strcmp(get(ah,'Visible'),'off')
  426.     fig.AxesVisible = 'off';
  427. else
  428.     fig.AxesVisible = 'on';
  429. end
  430.  
  431. % Try to extract bases by comparing Ticks with TickLabels
  432. XBase   = [];
  433. xTicks  = get (ah, 'XTick');
  434. xLabels = get (ah, 'XTickLabel'); % array of chars or cell array
  435. if length (xTicks) == size (xLabels, 1),
  436.     if (~ iscell (xLabels)) && (~ isempty (str2num (xLabels))) % labels are numeric
  437.         bases = xTicks ./ transpose (str2num (xLabels));
  438.         [valMin,idxMin] = min (bases);
  439.         if valMin == max (bases), % single value
  440.             XBase = log10 (bases (idxMin)); % XBase equivalent to Matlab figure
  441.         end
  442.     end
  443. end
  444. % Extrace bases
  445. fig.XLim=get(ah,'XLim');
  446. if isempty (XBase), % extrace base manually
  447.     if log10(fig.XLim(2)-fig.XLim(1)) > 3 % round towards infinity for positiv bases
  448.         fig.XBase=ceil(log10(abs(fig.XLim(2)-fig.XLim(1))));
  449.     elseif log10(fig.XLim(2)-fig.XLim(1)) < -2
  450.         fig.XBase=floor(log10(abs(fig.XLim(2)-fig.XLim(1))));
  451.     else
  452.         fig.XBase=1; % standard
  453.     end
  454. else
  455.     fig.XBase = XBase; % use base from Figure
  456. end
  457.  
  458. YBase   = [];
  459. yTicks  = get (ah, 'YTick');
  460. yLabels = get (ah, 'YTickLabel'); % array of chars or cell array
  461. if length (yTicks) == size (yLabels, 1),
  462.     if (~ iscell (yLabels)) && (~ isempty (str2num (yLabels))) % labels are numeric
  463.         bases = yTicks ./ transpose (str2num (yLabels));
  464.         [valMin,idxMin] = min (bases);
  465.         if valMin == max (bases), % single value
  466.             YBase = log10 (bases (idxMin)); % XBase equivalent to Matlab figure
  467.         end
  468.     end
  469. end
  470. % Extrace bases
  471. fig.YLim=get(ah,'YLim');
  472. if isempty (YBase), % extrace base manually
  473.     if log10(fig.YLim(2)-fig.YLim(1)) > 3 % round towards infinity for positiv bases
  474.         fig.YBase=ceil(log10(abs(fig.YLim(2)-fig.YLim(1))));
  475.     elseif log10(fig.YLim(2)-fig.YLim(1)) < -2
  476.         fig.YBase=floor(log10(abs(fig.YLim(2)-fig.YLim(1))));
  477.     else
  478.         fig.YBase=1; % standard
  479.     end
  480. else
  481.     fig.YBase = YBase; % use base from Figure
  482. end
  483.  
  484. % extract grids and ticks
  485. if strcmp(get(ah,'XGrid'),'on'),        fig.XGrid='on';        else fig.XGrid='off';        end
  486. if strcmp(get(ah,'XMinorGrid'),'on'),   fig.XMinorGrid='on';   else fig.XMinorGrid='off';   end
  487. if strcmp(get(ah,'XMinorTick'),'on'),   fig.XMinorTick='on';   else fig.XMinorTick='off';   end
  488. if strcmp(get(ah,'YGrid'),'on'),        fig.YGrid='on';        else fig.YGrid='off';        end
  489. if strcmp(get(ah,'YMinorGrid'),'on'),   fig.YMinorGrid='on';   else fig.YMinorGrid='off';   end
  490. if strcmp(get(ah,'YMinorTick'),'on'),   fig.YMinorTick='on';   else fig.YMinorTick='off';   end
  491. fig.GridLineStyle=get(ah,'gridlinestyle'); fig.GridLineStyleTeX = convert_lineStyle(fig.GridLineStyle);
  492. fig.MinorGridLineStyle=get(ah,'minorgridlinestyle'); fig.MinorGridLineStyleTeX = convert_lineStyle(fig.MinorGridLineStyle);
  493. [legh,object_h,plot_h,fig.LegendStr] = legend(ah); % get legend information
  494. legend_org = legh; % copy original legend
  495. if not(isempty(legh)), % if a legend is plotted
  496.     fig.LegendLoc=get(legh,'Location'); % get location
  497.     %     if strcmp(fig.LegendLoc,'none'), % no correct poition, ...
  498.     %         fig.LegendLoc='NorthWest';   % place NorthWest
  499.     %     end
  500. else
  501.     fig.LegendLoc=[];
  502. end
  503.  
  504. fig.XLabel = get(get(ah,'XLabel'),'String'); % save xlabel
  505. fig.YLabel = get(get(ah,'YLabel'),'String'); % save ylabel
  506. fig.Title  = get(get(ah,'Title'),'String');
  507. if (size(fig.XLabel,1)>1) || (size(fig.YLabel,1)>1) || (size(fig.Title,1)>1)
  508.     h=warndlg('Multiline labels or titles are not supported at the moment. Will keep the first line only!','Warning!','modal');
  509.     uiwait(h);
  510. end
  511. if size(fig.XLabel,1)>1,
  512.     %     for ii=2:size(fig.XLabel,1), % if more than one row, convert to one row
  513.     %         tmpstr1=[fig.XLabel(ii-1,:),'\\',fig.XLabel(ii,:)];
  514.     %     end
  515.     %     fig.XLabel=tmpstr1;
  516.     fig.XLabel=fig.XLabel(1,:);
  517. end
  518. if size(fig.YLabel,1)>1,
  519.     %     for ii=2:size(fig.YLabel,1), % if more than one row, convert to one row
  520.     %         tmpstr2=[fig.YLabel(ii-1,:),'\\',fig.YLabel(ii,:)];
  521.     %     end
  522.     %     fig.YLabel=tmpstr2;
  523.     fig.YLabel=fig.YLabel(1,:);
  524. end
  525. if size(fig.Title,1)>1,
  526.     %     for ii=2:size(fig.Title,1), % if more than one row, convert to one row
  527.     %         tmpstr3=[fig.Title(ii-1,:),'\\',fig.Title(ii,:)];
  528.     %     end
  529.     %     fig.Title=tmpstr3;
  530.     fig.Title=fig.Title(1,:);
  531. end
  532.  
  533. lshandles = get(ah,'Children'); % get all children of axes
  534. lsh = double(find(handle(lshandles),'-class','graph2d.lineseries')); % find plots
  535. lsh = [lsh; double(find(handle(lshandles),'-class','line'))]; % append 'line' plots
  536. lsh = flipud(lsh); % flip lsh in order to get the correct order
  537.  
  538. fig.LineStyle    = get(lsh,'LineStyle'); % Linestyle
  539. if not(iscell(fig.LineStyle)), fig.LineStyle={fig.LineStyle}; end
  540. fig.LineStyleTeX = convert_lineStyle(fig.LineStyle);
  541. fig.LineWidth    = get(lsh,'LineWidth'); % LineWidth
  542. if not(iscell(fig.LineWidth)), fig.LineWidth={fig.LineWidth}; end
  543. fig.Marker       = get(lsh,'Marker'); % Marker
  544. if not(iscell(fig.Marker)), fig.Marker={fig.Marker}; end
  545. fig.LineColor    = get(lsh,'Color'); % Linecolor
  546. if not(iscell(fig.LineColor)), fig.LineColor={fig.LineColor}; end
  547. fig.numLines=length(lsh);
  548. fig.FaceColor = {};
  549. for ll = 1 : fig.numLines
  550.     fig.FaceColor {end+1} = []; % empty facecolor field, this is used
  551.     % to check if the current line is part of a patch
  552. end
  553. fig.xdataLim=[inf,-inf]; % init
  554. fig.ydataLim=[inf,-inf];
  555. for ii=1:fig.numLines, % plot all children of axes again in linear scale
  556.     fig.xdata{ii} = get(lsh(ii),'XData'); % get data
  557.     fig.ydata{ii} = get(lsh(ii),'YData');
  558.     if fig.xLog, fig.xdata{ii} = log10(fig.xdata{ii}); end % make linear
  559.     if fig.yLog, fig.ydata{ii} = log10(fig.ydata{ii}); end % make linear
  560.     xmin=min(fig.xdata{ii}); xmax=max(fig.xdata{ii});
  561.     if xmin<fig.xdataLim(1), fig.xdataLim(1)=xmin; end % update if smaller
  562.     if xmax>fig.xdataLim(2), fig.xdataLim(2)=xmax; end % update if greater
  563.     ymin=min(fig.ydata{ii}); ymax=max(fig.ydata{ii});
  564.     if ymin<fig.ydataLim(1), fig.ydataLim(1)=ymin; end % update if smaller
  565.     if ymax>fig.ydataLim(2), fig.ydataLim(2)=ymax; end % update if greater
  566. end
  567.  
  568.  
  569. % Evaluate patches (Patches are treated as lines)
  570. lsh = double (find (handle (lshandles), '-class', 'patch'));
  571. lsh = flipud (lsh); % flip lsh in order to get the correct order
  572. numPatches = length(lsh);
  573.  
  574. if ~ isempty (lsh), % patches have been found, append at the beginning
  575.    
  576.     % Linestyle
  577.     LineStyleP = get(lsh,'LineStyle');
  578.     if not(iscell(LineStyleP)), LineStyleP={LineStyleP}; end
  579.     for ll = 1 : length(fig.LineStyle)
  580.         LineStyleP{end+1, 1} = fig.LineStyle{ll};
  581.     end
  582.     fig.LineStyle    = LineStyleP;
  583.     fig.LineStyleTeX = convert_lineStyle(fig.LineStyle);
  584.    
  585.     % Linewidth
  586.     LineWidthP = get(lsh,'LineWidth');
  587.     if not(iscell(LineWidthP)), LineWidthP={LineWidthP}; end
  588.     for ll = 1 : length(fig.LineWidth)
  589.         LineWidthP {end+1, 1} = fig.LineWidth{ll};
  590.     end
  591.     fig.LineWidth = LineWidthP;
  592.    
  593.     % Marker
  594.     MarkerP       = get(lsh,'Marker'); % should be 'none'
  595.     if not(iscell(MarkerP)), MarkerP={MarkerP}; end
  596.     for ll = 1 : length(fig.Marker)
  597.         MarkerP{end+1, 1} = fig.Marker{ll};
  598.     end
  599.     fig.Marker = MarkerP;
  600.    
  601.    
  602.     % FaceColor as an additional field
  603.     % test = get(lsh)
  604.     FaceColorCData = get(lsh,'CData');
  605.     if not(iscell(FaceColorCData)), FaceColorCData = {FaceColorCData}; end
  606.     FaceColorP     = get(lsh,'FaceColor');
  607.     if not(iscell(FaceColorP)), FaceColorP = {FaceColorP}; end
  608.     [cmin, cmax] = caxis(ah);
  609.     cmap = colormap; % get the current colormap
  610.     m = size(cmap, 1); % number of different colors in the colormap
  611.     for ll = 1 : length(FaceColorP)
  612.         if isstr(FaceColorP{ll}), % test if FaceColor is given as a rgb value
  613.             % compute color index according to Matlab help 'caxis'
  614.            
  615.             % test if still vector
  616.             if length(FaceColorCData{ll}) > 1,
  617.                 % take first value
  618.                 FaceColorCData{ll} = FaceColorCData{ll}(1);
  619.             end
  620.             index = fix((FaceColorCData{ll}-cmin)/(cmax-cmin)*m)+1;
  621.             if index > m, index = m; end
  622.             FaceColorP{ll} = cmap(index,:);
  623.         end
  624.     end
  625.    
  626.     for ll = 1 : fig.numLines
  627.         FaceColorP {end+1} = fig.FaceColor{ll};
  628.     end
  629.     fig.FaceColor = FaceColorP;
  630.     if not(iscell(fig.FaceColor)), fig.FaceColor={fig.FaceColor}; end
  631.    
  632.     % EdgeColor -> LineColor
  633.     EdgeColorP = get(lsh,'EdgeColor');
  634.     if not(iscell(EdgeColorP)), EdgeColorP = {EdgeColorP}; end
  635.     for ll = 1 : fig.numLines
  636.         EdgeColorP{end+1} = fig.LineColor{ll};
  637.     end
  638.     fig.LineColor = EdgeColorP;
  639.     if not(iscell(fig.LineColor)), fig.LineColor={fig.LineColor}; end
  640.    
  641.     % fig.xdataLim=[inf,-inf]; % init, not necessary, already defined
  642.     % fig.ydataLim=[inf,-inf];
  643.     % plot all children of axes again in linear scale
  644.     for ii = 1 : numPatches,
  645.         xdata = get(lsh(ii),'XData'); % get data
  646.         Pxdata{ii} = [xdata; xdata(1)]; % each patch must have the
  647.         % first point as end point
  648.         ydata = get(lsh(ii),'YData');
  649.         Pydata{ii} = [ydata; ydata(1)];
  650.         if fig.xLog, Pxdata{ii} = log10(Pxdata{ii}); end % make linear
  651.         if fig.yLog, Pydata{ii} = log10(Pydata{ii}); end % make linear
  652.         xmin=min(Pxdata{ii}); xmax=max(Pxdata{ii});
  653.         if xmin<fig.xdataLim(1), fig.xdataLim(1)=xmin; end % update if smaller
  654.         if xmax>fig.xdataLim(2), fig.xdataLim(2)=xmax; end % update if greater
  655.         ymin=min(Pydata{ii}); ymax=max(Pydata{ii});
  656.         if ymin<fig.ydataLim(1), fig.ydataLim(1)=ymin; end % update if smaller
  657.         if ymax>fig.ydataLim(2), fig.ydataLim(2)=ymax; end % update if greater
  658.     end
  659.    
  660.     for ii=1:fig.numLines, % plot all children of axes again in linear scale
  661.         Pxdata{end+1} = fig.xdata{ii};
  662.         Pydata{end+1} = fig.ydata{ii};
  663.     end
  664.     fig.xdata = Pxdata;
  665.     fig.ydata = Pydata;
  666.     fig.numLines = fig.numLines + numPatches;
  667.    
  668.    
  669. end
  670.  
  671.  
  672. fig.XTick=get(ah,'XTick');
  673. fig.XTickLabel=[]; % init
  674. if strcmp (get (ah, 'XTickLabelMode'), 'auto'),
  675.     for ii=1:length(fig.XTick), % set all latex strings for XTickLabel
  676.         fig.XTickLabel{ii}    = [num2str(fig.XTick(ii))];
  677.         fig.XTickLabelTex{ii} = ['$',num2str(fig.XTick(ii)),'$'];
  678.     end
  679. else
  680.     fig.XTickLabel    = convert_TickLabels2Cell (fig.XTick, get(ah,'XTickLabel'));
  681.     if ~ text_contains_dollarsymbol (fig.XTickLabel)
  682.         fig.XTickLabelTex = convert_text_to_latex (fig.XTickLabel);
  683.     else
  684.         fig.XTickLabelTex = fig.XTickLabel; % already TeX format
  685.     end
  686. end
  687.  
  688. if fig.xLog,
  689.     XTickNew = log10(fig.XTick);
  690.     XLimNew  = log10(fig.XLim);
  691.     if XLimNew(2) - XLimNew(1) < 1, % too small for logarithmic scale
  692.         XTickNew = [floor(fig.xdataLim(1)):1:ceil(fig.xdataLim(2))];
  693.         XLimNew  = [floor(fig.xdataLim(1)),ceil(fig.xdataLim(2))];
  694.     end
  695.     if (length(XTickNew) == length(fig.XTick)) && ... % maintain old labels
  696.             (strcmp (get (ah, 'XTickLabelMode'), 'manual'))
  697.         % do nothing
  698.     else
  699.         for ii=1:length(fig.XTick), % update latex strings for XTickLabel
  700.             fig.XTickLabel{ii}    = ['10^',num2str(XTickNew(ii))];
  701.             fig.XTickLabelTex{ii} = ['$10^{',num2str(XTickNew(ii)),'}$'];
  702.         end
  703.     end
  704.     fig.XTick = XTickNew;
  705.     fig.XLim  = XLimNew;
  706. end
  707.  
  708.  
  709.  
  710. fig.YTick=get(ah,'YTick');
  711. fig.YTickLabel=[]; % init
  712. if strcmp (get (ah, 'YTickLabelMode'), 'auto'),
  713.     for ii=1:length(fig.YTick), % set all latex strings for XTickLabel
  714.         fig.YTickLabel{ii}    = [num2str(fig.YTick(ii))];
  715.         fig.YTickLabelTex{ii} = ['$',num2str(fig.YTick(ii)),'$'];
  716.     end
  717. else
  718.     fig.YTickLabel    = convert_TickLabels2Cell (fig.YTick, get(ah,'YTickLabel'));
  719.     if ~ text_contains_dollarsymbol (fig.YTickLabel)
  720.         fig.YTickLabelTex = convert_text_to_latex (fig.YTickLabel);
  721.     else
  722.         fig.YTickLabelTex = fig.YTickLabel; % already TeX format
  723.     end
  724. end
  725.  
  726. if fig.yLog,
  727.     YTickNew = log10(fig.YTick);
  728.     YLimNew  = log10(fig.YLim);
  729.     if YLimNew(2) - YLimNew(1) < 1, % too small for logarithmic scale
  730.         YTickNew = [floor(fig.ydataLim(1)):1:ceil(fig.ydataLim(2))];
  731.         YLimNew  = [floor(fig.ydataLim(1)),ceil(fig.ydataLim(2))];
  732.     end
  733.     if (length(YTickNew) == length(fig.YTick)) && ... % maintain old labels
  734.             (strcmp (get (ah, 'YTickLabelMode'), 'manual'))
  735.         % do nothing
  736.     else
  737.         for ii=1:length(fig.YTick), % update latex strings for XTickLabel
  738.             fig.YTickLabel{ii}    = ['10^']; % no exponent, dummy, just for visualization
  739.             fig.YTickLabelTex{ii} = ['$10^{',num2str(YTickNew(ii)),'}$'];
  740.         end
  741.     end
  742.     fig.YTick = YTickNew;
  743.     fig.YLim  = YLimNew;
  744. end
  745.  
  746.  
  747.  
  748. % Test for too extrem X-values in linear case
  749. fig.XLabelPost = '';
  750. if not(fig.xLog) && (fig.XBase>2 || fig.XBase<-2), % if not logarithmic
  751.     % change the following variables:
  752.     % xdata, xdataLim, XTick, XTickLabel, XTickLabelTex, XLim
  753.     for ii=1:fig.numLines, % plot all children of axes again in linear scale
  754.         fig.xdata{ii}=fig.xdata{ii}/(10^fig.XBase);
  755.     end
  756.     fig.xdataLim=fig.xdataLim/(10^fig.XBase);
  757.     fig.XTick=fig.XTick/(10^fig.XBase);
  758.     fig.XLim=fig.XLim/(10^fig.XBase);
  759.     if strcmp (get (ah, 'XTickLabelMode'), 'auto'),
  760.         for ii=1:length(fig.XTick), % set all latex strings for XTickLabel
  761.             fig.XTickLabel{ii}    = [num2str(fig.XTick(ii))];%,'e',num2str(fig.XBase)];
  762.             fig.XTickLabelTex{ii} = ['$',num2str(fig.XTick(ii)),'$'];
  763.         end
  764.         fig.XLabelPost = [' $ \cdot 10^{',num2str(fig.XBase),'}$'];
  765.     end
  766. end
  767.  
  768. % Test for too extrem Y-values in linear case
  769. fig.YLabelPost = '';
  770. if not(fig.yLog) && (fig.YBase>2 || fig.YBase<-2), % if not logarithmic
  771.     % change the following variables:
  772.     % ydata, ydataLim, YTick, YTickLabel, YTickLabelTex, YLim
  773.     for ii=1:fig.numLines, % plot all children of axes again in linear scale
  774.         fig.ydata{ii}=fig.ydata{ii}/(10^fig.YBase);
  775.     end
  776.     fig.ydataLim=fig.ydataLim/(10^fig.YBase);
  777.     fig.YTick=fig.YTick/(10^fig.YBase);
  778.     fig.YLim=fig.YLim/(10^fig.YBase);
  779.     if strcmp (get (ah, 'YTickLabelMode'), 'auto'),
  780.         for ii=1:length(fig.YTick), % set all latex strings for YTickLabel
  781.             fig.YTickLabel{ii}    = [num2str(fig.YTick(ii))];%,'e',num2str(fig.YBase)];
  782.             fig.YTickLabelTex{ii} = ['$',num2str(fig.YTick(ii)),'$'];
  783.         end
  784.         fig.YLabelPost = [' $ \cdot 10^{',num2str(fig.YBase),'}$'];
  785.     end
  786. end
  787.  
  788. % extract annotations and convert the x- and y- values
  789. % Textarrows
  790. fig.TextarrowsStr=[]; %init
  791. allhandles = findall(fh);
  792. anhar = double(find(handle(allhandles),'-class','scribe.textarrow'));
  793. anhar = anhar(1:end/2); % take only the first half
  794. for ii= 1:length(anhar),
  795.     text_ta = get(anhar(ii),'String');
  796.     if ischar(text_ta) % for a specific reason that I can't figure out,
  797.         % it is a char array here, -> convert
  798.         for jj = 1: size(text_ta,1), % all rows
  799.             text_ta_out{jj,1} = text_ta(jj,:);
  800.         end
  801.         fig.TextarrowsStr{ii}   = text_ta_out; % copy
  802.     else
  803.         fig.TextarrowsStr{ii}   = text_ta;
  804.     end
  805.     fig.TextarrowsX(ii,:)   = get(anhar(ii),'X'); % normalized figure units
  806.     fig.TextarrowsY(ii,:)   = get(anhar(ii),'Y');
  807.     fig.TextarrowsRot(ii)   = 180 + 180/pi ...
  808.         * atan2(fig.TextarrowsY(ii,2)-fig.TextarrowsY(ii,1), ...
  809.         fig.TextarrowsX(ii,2)-fig.TextarrowsX(ii,1));
  810.     fig.TextarrowsColor{ii} = get(anhar(ii),'color');
  811.     fig.TextarrowsLineStyle{ii} = get(anhar(ii),'linestyle');
  812.     fig.TextarrowsHorizontalAlignment{ii} = get(anhar(ii),'HorizontalAlignment');
  813. end
  814. if ~isempty(anhar)
  815.     % convert relative figure positions to x-and y-values
  816.     set(ah,'Units','normalized')
  817.     pos=get(ah,'Position');
  818.     XY1=pos(1:2); Width=pos(3:4);
  819.     fig.TextarrowsX=(fig.TextarrowsX-XY1(1))./Width(1); % normalized axes units
  820.     fig.TextarrowsY=(fig.TextarrowsY-XY1(2))./Width(2);
  821.     fig.TextarrowsX=fig.TextarrowsX.*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1); % matched x-units
  822.     fig.TextarrowsY=fig.TextarrowsY.*(fig.YLim(2)-fig.YLim(1))+fig.YLim(1); % matched y-units
  823. end
  824. % TextBoxes
  825. fig.TextBoxesStr=[]; %init
  826. anhtb = double(find(handle(allhandles),'-class','scribe.textbox'));
  827. anhtb = anhtb(1:end/2); % take only the first half
  828. for ii= 1:length(anhtb),
  829.     text_tb = get(anhtb(ii),'String');
  830.     if ischar(text_tb) % for a specific reason that I can't figure out,
  831.         % it is a char array here, -> convert
  832.         for jj = 1: size(text_tb,1), % all rows
  833.             text_tb_out{jj,1} = text_tb(jj,:);
  834.         end
  835.         fig.TextBoxesStr{ii}   = text_tb_out; % copy
  836.     else
  837.         fig.TextBoxesStr{ii}   = text_tb;
  838.     end
  839.     fig.TextBoxesPosition(ii,:)   = get(anhtb(ii),'Position'); % normalized figure units
  840.     fig.TextBoxesColor{ii} = get(anhtb(ii),'Color');
  841.     fig.TextBoxesLineStyle{ii} = get(anhtb(ii),'LineStyle');
  842.     fig.TextBoxesHorizontalAlignment{ii} = get(anhtb(ii),'HorizontalAlignment');
  843. end
  844. if ~isempty(anhtb)
  845.     % convert relative figure positions to x-and y-values
  846.     set(ah,'Units','normalized')
  847.     pos=get(ah,'Position');
  848.     XY1=pos(1:2); Width=pos(3:4);
  849.     fig.TextBoxesX = (fig.TextBoxesPosition(:,1)-XY1(1))./Width(1); % normalized axes units
  850.     fig.TextBoxesY = (fig.TextBoxesPosition(:,2)-XY1(2))./Width(2);
  851.     fig.TextBoxesX = fig.TextBoxesX.*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1); % matched x-units
  852.     fig.TextBoxesY = fig.TextBoxesY.*(fig.YLim(2)-fig.YLim(1))+fig.YLim(1); % matched y-units
  853. end
  854.  
  855. % extract box
  856. if strcmp(get(ah,'Box'),'on'), fig.Box='on'; else fig.Box='off'; end
  857.  
  858. % if none of the strings contains a '$', set converting on by default
  859. if  ~ text_contains_dollarsymbol (fig.LegendStr)
  860.     fig.LegendStr = convert_text_to_latex (fig.LegendStr);
  861. end
  862. if  ~ text_contains_dollarsymbol (fig.XLabel)
  863.     fig.XLabel = convert_text_to_latex (fig.XLabel);
  864. end
  865. if  ~ text_contains_dollarsymbol (fig.YLabel)
  866.     fig.YLabel = convert_text_to_latex (fig.YLabel);
  867. end
  868. if  ~ text_contains_dollarsymbol (fig.Title)
  869.     fig.Title = convert_text_to_latex (fig.Title);
  870. end
  871. for kk = 1 : length (fig.TextarrowsStr)
  872.     if ~text_contains_dollarsymbol(fig.TextarrowsStr{kk})
  873.         fig.TextarrowsStr{kk} = convert_text_to_latex (fig.TextarrowsStr{kk});
  874.     end
  875. end
  876. for kk = 1 : length (fig.TextBoxesStr)
  877.     if ~text_contains_dollarsymbol(fig.TextBoxesStr{kk})
  878.         fig.TextBoxesStr{kk} = convert_text_to_latex (fig.TextBoxesStr{kk});
  879.     end
  880. end
  881.  
  882. %%
  883.  
  884. % Extract Data of second yaxis
  885. fig.YMinorTick2='off'; % init
  886. if ~isempty(ahSecond), % process second y-axis
  887.     % all variables of the second axis are same as first with an extra "2":
  888.    
  889.     % Test if Scales are log
  890.     fig.xLog2=fig.xLog; % x-axis is equal
  891.     if strcmp(get(ahSecond,'YScale'),'log'), fig.yLog2=1; else fig.yLog2=0; end
  892.    
  893.     % Extrace bases
  894.     fig.XLim2=fig.XLim;
  895.     fig.XBase2=fig.XBase;
  896.     YBase2  = [];
  897.     yTicks  = get (ahSecond, 'YTick');
  898.     yLabels = get (ahSecond, 'YTickLabel'); % array of chars or cell array
  899.     if length (yTicks) == size (yLabels, 1),
  900.         if (~ iscell (yLabels)) && (~ isempty (str2num (yLabels))) % labels are numeric
  901.             bases = yTicks ./ transpose (str2num (yLabels));
  902.             [valMin,idxMin] = min (bases);
  903.             if valMin == max (bases), % single value
  904.                 YBase2 = log10 (bases (idxMin)); % YBase equivalent to Matlab figure
  905.             end
  906.         end
  907.     end
  908.     fig.YLim2=get(ahSecond,'YLim');
  909.     if isempty (YBase2), % extrace base manually
  910.         if log10(fig.YLim2(2)-fig.YLim2(1)) > 3 % round towards infinity for positiv bases
  911.             fig.YBase2=ceil(log10(abs(fig.YLim2(2)-fig.YLim2(1))));
  912.         elseif log10(fig.YLim2(2)-fig.YLim2(1)) < -2
  913.             fig.YBase2=floor(log10(abs(fig.YLim2(2)-fig.YLim2(1))));
  914.         else
  915.             fig.YBase2=1; % standard
  916.         end
  917.     else
  918.         fig.YBase2 = YBase2; % use base from Figure
  919.     end
  920.    
  921.     % extract grids and ticks
  922.     fig.XGrid2='off';
  923.     fig.XMinorGrid2='off';
  924.     fig.XMinorTick2='off';
  925.     fig.XTick2='off';
  926.     fig.YGrid2='off';
  927.     fig.YMinorGrid2='off';
  928.     if strcmp(get(ahSecond,'YMinorTick'),'on'),   fig.YMinorTick2='on';   else fig.YMinorTick2='off';   end
  929.     fig.LegendLoc2=[]; % no second legend, all information is in first one
  930.     fig.XLabel2 = '';
  931.     fig.YLabel2 = get(get(ahSecond,'YLabel'),'String'); % save ylabel
  932.     if  ~ text_contains_dollarsymbol (fig.YLabel2)
  933.         fig.YLabel2 = convert_text_to_latex (fig.YLabel2);
  934.     end
  935.    
  936.     % extrace data of second axis
  937.     lshandles2 = get(ahSecond,'Children'); % get all children of axes
  938.     lsh2 = double(find(handle(lshandles2),'-class','graph2d.lineseries'));
  939.     lsh2 = [lsh2; double(find(handle(lshandles2),'-class','line'))]; % append 'line' plots
  940.     lsh2 = flipud(lsh2); % flip lsh in order to get the correct order
  941.     fig.LineStyle2    = get(lsh2,'LineStyle'); % Linestyle
  942.     if not(iscell(fig.LineStyle2)), fig.LineStyle2={fig.LineStyle2}; end
  943.     fig.LineStyleTeX2 = convert_lineStyle(fig.LineStyle2);
  944.     fig.LineWidth2    = get(lsh2,'LineWidth'); % LineWidth
  945.     if not(iscell(fig.LineWidth2)), fig.LineWidth2={fig.LineWidth2}; end
  946.     fig.Marker2       = get(lsh2,'Marker'); % Marker
  947.     if not(iscell(fig.Marker2)), fig.Marker2={fig.Marker2}; end
  948.     fig.LineColor2    = get(lsh2,'Color'); % Linecolor
  949.     if not(iscell(fig.LineColor2)), fig.LineColor2={fig.LineColor2}; end
  950.     fig.numLines2=length(lsh2);
  951.     for ll = 1 : fig.numLines2
  952.         fig.FaceColor {end+1} = []; % empty facecolor field,
  953.     end
  954.     fig.xdataLim2=fig.xdataLim;
  955.     fig.ydataLim2=[inf,-inf]; % init
  956.     for ii=1:fig.numLines2, % plot all children of axes again in linear scale
  957.         fig.xdata2{ii} = get(lsh2(ii),'XData'); % get data
  958.         fig.ydata2{ii} = get(lsh2(ii),'YData');
  959.         if fig.xLog2, fig.xdata2{ii} = log10(fig.xdata2{ii}); end % make linear
  960.         if fig.yLog2, fig.ydata2{ii} = log10(fig.ydata2{ii}); end % make linear
  961.         ymin=min(fig.ydata2{ii}); ymax=max(fig.ydata2{ii});
  962.         if ymin<fig.ydataLim2(1), fig.ydataLim2(1)=ymin; end % update if smaller
  963.         if ymax>fig.ydataLim2(2), fig.ydataLim2(2)=ymax; end % update if greater
  964.     end
  965.    
  966.     fig.YTick2=get(ahSecond,'YTick');
  967.     fig.YTickLabel2=[]; % init
  968.     if strcmp (get (ahSecond, 'YTickLabelMode'), 'auto'),
  969.         for ii=1:length(fig.YTick2), % set all latex strings for XTickLabel
  970.             fig.YTickLabel2{ii}    = [num2str(fig.YTick2(ii))];
  971.             fig.YTickLabelTex2{ii} = ['$',num2str(fig.YTick2(ii)),'$'];
  972.         end
  973.     else
  974.         fig.YTickLabel2    = convert_TickLabels2Cell (fig.YTick2, get(ahSecond,'YTickLabel'));
  975.         if ~ text_contains_dollarsymbol (fig.YTickLabel2)
  976.             fig.YTickLabelTex2 = convert_text_to_latex (fig.YTickLabel2);
  977.         else
  978.             fig.YTickLabelTex2 = fig.YTickLabel2; % already TeX format
  979.         end
  980.     end
  981.     if fig.yLog2,
  982.         fig.YTick2=log10(fig.YTick2);
  983.         fig.YLim2=log10(fig.YLim2);
  984.         if fig.YLim2(2)-fig.YLim2(1)<1, % too small for logarithmic scale
  985.             fig.YTick2=[floor(fig.ydataLim2(1)):1:ceil(fig.ydataLim2(2))];
  986.             fig.YLim2=[floor(fig.ydataLim2(1)),ceil(fig.ydataLim2(2))];
  987.         end
  988.         for ii=1:length(fig.YTick2), % set all latex strings for XTickLabel
  989.             fig.YTickLabel2{ii}    = ['10^']; % no exponent, dummy, just for visualization
  990.             fig.YTickLabelTex2{ii} = ['$10^{',num2str(fig.YTick2(ii)),'}$'];
  991.         end
  992.     end
  993.    
  994.     % Test for too extrem X-values in linear case
  995.     if not(fig.xLog) && (fig.XBase>2 || fig.XBase<-1), % if not logarithmic
  996.         % change xdata2:
  997.         for ii=1:fig.numLines2, % plot all children of axes again in linear scale
  998.             fig.xdata2{ii}=fig.xdata2{ii}/(10^fig.XBase);
  999.         end
  1000.     end
  1001.    
  1002.     % Test for too extrem Y-values in linear case
  1003.     fig.YLabelPost2 = '';
  1004.     if not(fig.yLog2) && (fig.YBase2>2 || fig.YBase2<-2), % if not logarithmic
  1005.         % change the following variables:
  1006.         % ydata, ydataLim, YTick, YTickLabel, YTickLabelTex, YLim
  1007.         for ii=1:fig.numLines2, % plot all children of axes again in linear scale
  1008.             fig.ydata2{ii}=fig.ydata2{ii}/(10^fig.YBase2);
  1009.         end
  1010.         fig.ydataLim2=fig.ydataLim2/(10^fig.YBase2);
  1011.         fig.YTick2=fig.YTick2/(10^fig.YBase2);
  1012.         fig.YLim2=fig.YLim2/(10^fig.YBase2);
  1013.         if strcmp (get (ahSecond, 'YTickLabelMode'), 'auto'),
  1014.             for ii=1:length(fig.YTick2), % set all latex strings for YTickLabel
  1015.                 fig.YTickLabel2{ii}    = [num2str(fig.YTick2(ii))];%,'e',num2str(fig.YBase)];
  1016.                 fig.YTickLabelTex2{ii} = ['$',num2str(fig.YTick2(ii)),'$'];
  1017.             end
  1018.             fig.YLabelPost2 = [' $ \cdot 10^{',num2str(fig.YBase2),'}$'];
  1019.         end
  1020.     end
  1021.    
  1022.     % convert y-data, and y-ticks
  1023.     for ii=1:fig.numLines2, % convert all y-data in order to match with the first axes
  1024.         fig.ydata2{ii}=((fig.ydata2{ii}-fig.YLim2(1))/(fig.YLim2(2)-fig.YLim2(1))*...
  1025.             (fig.YLim(2)-fig.YLim(1)))+fig.YLim(1);
  1026.     end
  1027.     fig.YTick2Tex=((fig.YTick2-fig.YLim2(1))/(fig.YLim2(2)-fig.YLim2(1))*...
  1028.         (fig.YLim(2)-fig.YLim(1)))+fig.YLim(1);
  1029.     yAxisCenversionFac=(fig.YLim(2)-fig.YLim(1))/(fig.YLim2(2)-fig.YLim2(1));
  1030.    
  1031.     % append data
  1032.     for ii=1:fig.numLines2, % append data
  1033.         fig.xdata{fig.numLines+ii}=fig.xdata2{ii};
  1034.         fig.ydata{fig.numLines+ii}=fig.ydata2{ii};
  1035.         fig.LineColor{fig.numLines+ii}=fig.LineColor2{ii};
  1036.         fig.LineStyle{fig.numLines+ii}=fig.LineStyle2{ii};
  1037.         fig.LineWidth{fig.numLines+ii}=fig.LineWidth2{ii};
  1038.         fig.Marker{fig.numLines+ii}=fig.Marker2{ii};
  1039.     end
  1040.     fig.numLines=fig.numLines+fig.numLines2; % update number of lines
  1041. end
  1042.  
  1043.  
  1044. %%
  1045.  
  1046. % PLOT EXTRACTED DATA IN NEW FIGURE
  1047.  
  1048. % check for docked DefaultFigureWindowStyle
  1049. if strcmp (get(0,'DefaultFigureWindowStyle'), 'docked')
  1050.     warning(['fig2TexPS won''t work with docked figures correctly. ', ...
  1051.         'Please switch of this behavior by typing: ', ...
  1052.         'set(0,''DefaultFigureWindowStyle'',''normal''). ', ...
  1053.         'The docked behavior can be set afterwards back to: ',...
  1054.         'set(0,''DefaultFigureWindowStyle'',''docked'')'])
  1055. end
  1056.  
  1057. % create new figure and new axes that will have linear axes:
  1058. fig.figh=figure('Name','Figure outline that will be converted to LaTeX',...
  1059.     'HitTest','off','MenuBar','none',...
  1060.     'NumberTitle','off','Resize','off');
  1061. fig.axh=axes;
  1062.  
  1063. for ii=1:fig.numLines,
  1064.     plot(fig.axh,fig.xdata{ii},fig.ydata{ii},...
  1065.         'Color',fig.LineColor{ii},...
  1066.         'LineStyle',fig.LineStyle{ii},...
  1067.         'LineWidth',fig.LineWidth{ii},...
  1068.         'Marker',fig.Marker{ii});
  1069.     hold on;
  1070. end
  1071. set(fig.axh, ...
  1072.     'XGrid',fig.XGrid,...
  1073.     'YGrid',fig.YGrid,...
  1074.     'Box',fig.Box,...
  1075.     'gridlinestyle',fig.GridLineStyle,...
  1076.     'minorgridlinestyle',fig.MinorGridLineStyle,...
  1077.     'Visible',fig.AxesVisible);
  1078. if not(fig.xLog), % if not logarithmic, set minor grid
  1079.     set(fig.axh,'XMinorGrid',fig.XMinorGrid);
  1080.     set(fig.axh,'XMinorTick',fig.XMinorTick);
  1081. end
  1082. if not(fig.yLog),
  1083.     set(fig.axh,'YMinorGrid',fig.YMinorGrid);
  1084.     set(fig.axh,'YMinorTick',fig.YMinorTick);
  1085. end
  1086. set(fig.axh,'XTick',fig.XTick,'XLim',fig.XLim);
  1087. set(fig.axh,'XTickLabel',fig.XTickLabel)
  1088. set(fig.axh,'YTick',fig.YTick,'YLim',fig.YLim);
  1089. set(fig.axh,'YTickLabel',fig.YTickLabel)
  1090. set(fig.axh,'FontSize',globals.labelsep)
  1091. xlabel(fig.XLabel,'FontSize',globals.labelsep,'interpreter','none');
  1092. ylabel(fig.YLabel,'FontSize',globals.labelsep,'interpreter','none');
  1093. title(fig.Title,'FontSize',globals.labelsep,'interpreter','none');
  1094. if not(isempty(fig.LegendLoc)), % a legend is replotted
  1095.     legend(fig.axh,fig.LegendStr,'Location',fig.LegendLoc,'Interpreter','none')
  1096. end
  1097. if ~isempty(ahSecond), % process second y-axis
  1098.     fig.axh2=axes('Units',get(fig.axh,'Units'),...
  1099.         'Position',get(fig.axh,'Position'),...
  1100.         'Parent',get(fig.axh,'Parent'),...
  1101.         'XAxisLocation','bottom','YAxisLocation','right',...
  1102.         'Color','none','XColor','k','XTick',[],'YTickLabel',fig.YTickLabel2,...
  1103.         'YColor','k','YLim',fig.YLim2,'YTick',fig.YTick2,'YMinorTick',fig.YMinorTick2);
  1104.     ylabel(fig.YLabel2,'FontSize',globals.labelsep,'interpreter','none');
  1105. end
  1106.  
  1107. movegui(fig.figh,'center'); % shift figure to screen center
  1108.  
  1109.  
  1110.  
  1111. %%
  1112.  
  1113. % FIGURE GEOMETRY SETTINGS
  1114.  
  1115. [fig,globals] = update_figure_geometry(fig,globals); % subfunction GUI
  1116. if exit_flag,
  1117.     warning(s); % turn on specified warnings again
  1118.     return,
  1119. end
  1120.  
  1121. fp=get(fig.figh,'Position');
  1122.  
  1123. set(fig.axh,'Units','normalized'); ap=get(fig.axh,'Position');
  1124. ti=get(fig.axh,'TightInset'); % [left bottom right top]
  1125.  
  1126. if ~isempty(ahSecond),
  1127.     set(fig.axh2,'Units','normalized');
  1128.     ti2=get(fig.axh2,'TightInset'); % [left bottom right top]
  1129.     ti(3)=ti2(3); % update extra space on the right side caused by second y-label
  1130. end
  1131.  
  1132. % test if axes should be centered, if yes, adapt either left ti(1) or right
  1133. % ti(1) to the greater one
  1134. if globals.centerAxes==1,
  1135.     if ti(3)<ti(1), ti(3)=ti(1); else ti(1)=ti(3); end
  1136. end
  1137. % apPlusTight=[ap(1)-ti(1),ap(2)-ti(2),ap(3)+ti(1)+ti(3),ap(4)+ti(2)+ti(4)];
  1138.  
  1139. DeltaXLim=fig.XLim(2)-fig.XLim(1);
  1140. xunit = 1/DeltaXLim;
  1141. DeltaYLim=fig.YLim(2)-fig.YLim(1);
  1142. yunit = globals.heightFactor/DeltaYLim;
  1143. % Here xunit and yunit are set in order that the width matches to the axes
  1144. % If the width of the figure shoud match to the figure, both xunit and
  1145. % yunit must be scaled down
  1146. if strcmp(globals.widthType,'figure'),
  1147.     % ap(3)       % normalized width of axes
  1148.     % ti(1)+ti(3) % normalized width of extra space
  1149.     totWidthNorm=ap(3)+ti(1)+ti(3);
  1150.     xunit=xunit*ap(3)/totWidthNorm; % scale
  1151.     yunit=yunit*ap(3)/totWidthNorm; % scale
  1152. %     StrFile{end+1}=['\providelength{\plotwidth}           \setlength{\plotwidth}{',num2str(globals.plotwidth),'cm}% width of the total figure']; % append next line
  1153. else
  1154. %     StrFile{end+1}=['\providelength{\plotwidth}           \setlength{\plotwidth}{',num2str(globals.plotwidth),'cm}% width of the axes only']; % append next line
  1155. end
  1156. % create the length, with options to re-write it.
  1157. if isnumeric(globals.plotwidth)
  1158.     newWidth = [num2str(globals.plotwidth),'cm'];
  1159. else
  1160.     newWidth = globals.plotwidth;
  1161. end
  1162. StrFile{end+1}='\ifx \plotwidth \undefined% if this is the first figure';
  1163. StrFile{end+1}=['    \providelength{\plotwidth} \setlength{\plotwidth}{',newWidth,'}%'];
  1164. StrFile{end+1}='\else% this figure is not the only one in the file';
  1165. StrFile{end+1}='  \ifdim \plotwidth=0pt%';
  1166. StrFile{end+1}=['    \setlength{\plotwidth}{',newWidth,'}%'];
  1167. StrFile{end+1}='  \fi%';
  1168. StrFile{end+1}='\fi%';
  1169.  
  1170.  
  1171. if ischar(globals.LineWidth)
  1172.     StrFile{end+1}=['\providelength{\LineWidth}           \setlength{\LineWidth}{',globals.LineWidth,'}%']; % append next line
  1173. else
  1174.     StrFile{end+1}=['\providelength{\LineWidth}           \setlength{\LineWidth}{',num2str(globals.LineWidth),'pt}%']; % append next line
  1175. end
  1176. if numPatches>0,
  1177.     if ischar(globals.EdgeLineWidth)
  1178.         StrFile{end+1}=['\providelength{\EdgeLineWidth}       \setlength{\EdgeLineWidth}{',globals.EdgeLineWidth,'}%']; % append next line
  1179.     else
  1180.         StrFile{end+1}=['\providelength{\EdgeLineWidth}       \setlength{\EdgeLineWidth}{',num2str(globals.EdgeLineWidth),'pt}%']; % append next line
  1181.     end
  1182. end
  1183.  
  1184.  
  1185. if ischar(globals.MarkerSize)
  1186.     StrFile{end+1}=['\providelength{\MarkerSize}          \setlength{\MarkerSize}{',globals.MarkerSize,'}%']; % append next line
  1187. else
  1188.     StrFile{end+1}=['\providelength{\MarkerSize}          \setlength{\MarkerSize}{',num2str(globals.MarkerSize),'pt}%']; % append next line
  1189. end
  1190. StrFile{end+1}=['\newrgbcolor{GridColor}{',num2str(globals.GridGreyFac),' ',num2str(globals.GridGreyFac),' ',num2str(globals.GridGreyFac),'}%'];
  1191. StrFile{end+1}='%';
  1192. StrFile{end+1}='% Begin Figure:-------------------------------------------';
  1193. tmpstr = '\psset{xunit=#1#\plotwidth,yunit=#2#\plotwidth}%';
  1194. StrFile{end+1}=strfill(tmpstr,{xunit,yunit});
  1195.  
  1196. if ~isempty(globals.tightInset_cm) && strcmp(globals.widthType,'axes'),
  1197.     % Here, the fixed borders are set
  1198.     figx1 = fig.XLim(1)-globals.tightInset_cm(1)/globals.plotwidth*DeltaXLim;
  1199.     figy1 = fig.YLim(1)-globals.tightInset_cm(2)/globals.plotwidth*DeltaYLim/globals.heightFactor;
  1200.     figx2 = fig.XLim(1)+DeltaXLim+globals.tightInset_cm(3)/globals.plotwidth*DeltaXLim;
  1201.     figy2 = fig.YLim(1)+DeltaYLim+globals.tightInset_cm(4)/globals.plotwidth*DeltaYLim/globals.heightFactor;
  1202. else
  1203.     if ~isempty(globals.tightInset_cm),
  1204.         % Here, conflict because of fixed figure size
  1205.         warning('The extra space setting will work correctly only when the width of the axes is specified!')
  1206.     end
  1207.     figx1 = fig.XLim(1)-ti(1)/ap(3)*DeltaXLim;
  1208.     figy1 = fig.YLim(1)-ti(2)/ap(4)*DeltaYLim;
  1209.     figx2 = fig.XLim(1)+(ap(3)+ti(3))/ap(3)*DeltaXLim;
  1210.     figy2 = fig.YLim(1)+(ap(4)+ti(4))/ap(4)*DeltaYLim;
  1211. end
  1212.  
  1213.  
  1214. tmpstr = '\begin{pspicture}(#1#,#2#)(#3#,#4#)%';
  1215. StrFile{end+1}=strfill(tmpstr,{figx1,figy1,figx2,figy2});
  1216.  
  1217. %%
  1218.  
  1219. % DRAW GRID AND AXES
  1220.  
  1221.  
  1222. % draw box for visualization
  1223. StrFile{end+1}='';
  1224. StrFile{end+1}='% Draw bounding box for test aspects: ----';
  1225. if globals.BoundingBox
  1226.     tmpstr = '\psframe(#1#,#2#)(#3#,#4#)';
  1227. else
  1228.     tmpstr = '% \psframe(#1#,#2#)(#3#,#4#)'; % with comments
  1229. end
  1230. StrFile{end+1}=strfill(tmpstr,{figx1,figy1,figx2,figy2});
  1231. tmpstr = '% Total width:  #1# cm';
  1232. TotalWidth_cm = globals.plotwidth*xunit*(figx2-figx1);
  1233. StrFile{end+1}=strfill(tmpstr,{TotalWidth_cm});
  1234. tmpstr = '% Total height: #1# cm';
  1235. TotalHeight_cm = globals.plotwidth*yunit*(figy2-figy1);
  1236. StrFile{end+1}=strfill(tmpstr,{TotalHeight_cm});
  1237.  
  1238. TickMajorLengthX=globals.TickMajorLengthRel*DeltaXLim; % length of the grid lines
  1239. TickMinorLengthX=globals.TickMinorLengthRel*DeltaXLim;
  1240. TickMajorLengthY=globals.TickMajorLengthRel*DeltaYLim/globals.heightFactor;
  1241. TickMinorLengthY=globals.TickMinorLengthRel*DeltaYLim/globals.heightFactor;
  1242.  
  1243. if strcmp(fig.AxesVisible,'on'), % draw only in this case
  1244.    
  1245.     % draw grid
  1246.     GLSTex=fig.GridLineStyleTeX{1}; % convert to char
  1247.     if strcmp(fig.XGrid,'on') || strcmp(fig.YGrid,'on') % At least one Grid
  1248.         StrFile{end+1}='';
  1249.         StrFile{end+1}='% Draw Grid: ----';
  1250.         if ischar(globals.MinorGridLineDotSep)
  1251.             StrFile={['\providelength{\MinorGridLineDotSep} \setlength{\MinorGridLineDotSep}{',globals.MinorGridLineDotSep,'}%'],StrFile{1:end}};
  1252.         else
  1253.             StrFile={['\providelength{\MinorGridLineDotSep} \setlength{\MinorGridLineDotSep}{',num2str(globals.MinorGridLineDotSep),'pt}%'],StrFile{1:end}};
  1254.         end
  1255.         if ischar(globals.MinorGridLineWidth)
  1256.             StrFile={['\providelength{\MinorGridLineWidth}  \setlength{\MinorGridLineWidth}{',globals.MinorGridLineWidth,'}%'],StrFile{1:end}};
  1257.         else
  1258.             StrFile={['\providelength{\MinorGridLineWidth}  \setlength{\MinorGridLineWidth}{',num2str(globals.MinorGridLineWidth),'pt}%'],StrFile{1:end}};
  1259.         end
  1260.         if ischar(globals.GridLineDotSep)
  1261.             StrFile={['\providelength{\GridLineDotSep}      \setlength{\GridLineDotSep}{',globals.GridLineDotSep,'}%'],StrFile{1:end}};
  1262.         else
  1263.             StrFile={['\providelength{\GridLineDotSep}      \setlength{\GridLineDotSep}{',num2str(globals.GridLineDotSep),'pt}%'],StrFile{1:end}};
  1264.         end
  1265.         if ischar(globals.GridLineWidth)
  1266.             StrFile={['\providelength{\GridLineWidth}       \setlength{\GridLineWidth}{',globals.GridLineWidth,'}%'],StrFile{1:end}};
  1267.         else
  1268.             StrFile={['\providelength{\GridLineWidth}       \setlength{\GridLineWidth}{',num2str(globals.GridLineWidth),'pt}%'],StrFile{1:end}};
  1269.         end
  1270.         if strcmp(fig.XGrid,'on') % xgrid
  1271.             StrFile{end+1}='% x-Grid:';
  1272.             for ii=1:length(fig.XTick), % x=const
  1273.                 StrFile{end+1}=['\psline[linestyle=',GLSTex,',dotsep=\GridLineDotSep,linewidth=\GridLineWidth,linecolor=GridColor](',num2str(fig.XTick(ii),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XTick(ii),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1274.             end
  1275.         end
  1276.         if strcmp(fig.YGrid,'on') % ygrid
  1277.             StrFile{end+1}='% y-Grid:';
  1278.             for ii=1:length(fig.YTick), % y=const
  1279.                 StrFile{end+1}=['\psline[linestyle=',GLSTex,',dotsep=\GridLineDotSep,linewidth=\GridLineWidth,linecolor=GridColor](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YTick(ii),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YTick(ii),globals.FloatingPointFormat),')'];
  1280.             end
  1281.         end
  1282.     end
  1283.    
  1284.     % draw minor grid
  1285.     subPoints_log=log10([2 3 4 5 6 7 8 9]);
  1286.     MGLSTex=fig.MinorGridLineStyleTeX{1}; % convert to char
  1287.     if strcmp(fig.XMinorGrid,'on') || strcmp(fig.YMinorGrid,'on') % At least one Grid
  1288.         StrFile{end+1}='';
  1289.         StrFile{end+1}='% Draw Minor Grid: ----';
  1290.         if strcmp(fig.XMinorGrid,'on') && fig.xLog==1 % XMinorGrid and log
  1291.             if length(fig.XTick)>1, % at least two points
  1292.                 if fig.XTick(2)-fig.XTick(1) == 1 % one decade per point
  1293.                     StrFile{end+1}='% x-Minor Grid:';
  1294.                     for ii=1:length(fig.XTick)-1, % x=const
  1295.                         for jj=1:length(subPoints_log),
  1296.                             if fig.XTick(ii)+subPoints_log(jj) <= fig.XLim(2),
  1297.                                 StrFile{end+1}=['\psline[linestyle=',MGLSTex,',dotsep=\MinorGridLineDotSep,linewidth=\MinorGridLineWidth,linecolor=GridColor](',num2str(fig.XTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1298.                             end
  1299.                         end
  1300.                     end
  1301.                 end
  1302.             end
  1303.         end
  1304.         if strcmp(fig.YMinorGrid,'on') && fig.yLog==1 % YMinorGrid and log
  1305.             if length(fig.YTick)>1, % at least two points
  1306.                 if fig.YTick(2)-fig.YTick(1) == 1 % one decade per point
  1307.                     StrFile{end+1}='% y-Minor Grid:';
  1308.                     for ii=1:length(fig.YTick)-1, % x=const
  1309.                         for jj=1:length(subPoints_log),
  1310.                             if fig.YTick(ii)+subPoints_log(jj) <= fig.YLim(2),
  1311.                                 StrFile{end+1}=['\psline[linestyle=',MGLSTex,',dotsep=\MinorGridLineDotSep,linewidth=\MinorGridLineWidth,linecolor=GridColor](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),')'];
  1312.                             end
  1313.                         end
  1314.                     end
  1315.                 end
  1316.             end
  1317.         end
  1318.     end
  1319.    
  1320.     % draw ticks
  1321.     StrFile{end+1}='';
  1322.     StrFile{end+1}='% Draw Ticks: ----';
  1323.     StrFile{end+1}='% x-Ticks:';
  1324.     for ii=1:length(fig.XTick), % x=const
  1325.         StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XTick(ii),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XTick(ii),globals.FloatingPointFormat),',',num2str(fig.YLim(1)+TickMajorLengthY,globals.FloatingPointFormat),')'];
  1326.     end
  1327.     StrFile{end+1}='% y-Ticks:';
  1328.     for ii=1:length(fig.YTick), % y=const
  1329.         StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YTick(ii),globals.FloatingPointFormat),')(',num2str(fig.XLim(1)+TickMajorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick(ii),globals.FloatingPointFormat),')'];
  1330.     end
  1331.     if ~isempty(ahSecond),
  1332.         StrFile{end+1}='% y-Ticks Second Axis:';
  1333.         for ii=1:length(fig.YTick2), % y=const
  1334.             StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XLim(2)-TickMajorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick2Tex(ii),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YTick2Tex(ii),globals.FloatingPointFormat),')'];
  1335.         end
  1336.     end
  1337.    
  1338.     % draw minor ticks
  1339.     if strcmp(fig.XMinorTick,'on') || strcmp(fig.YMinorTick,'on') || strcmp(fig.YMinorTick2,'on') % At least one Tick
  1340.         StrFile{end+1}='';
  1341.         StrFile{end+1}='% Draw Minor Ticks: ----';
  1342.         if strcmp(fig.XMinorTick,'on') && fig.xLog==1 % XMinorTick and log
  1343.             if length(fig.XTick)>1, % at least two points
  1344.                 if fig.XTick(2)-fig.XTick(1) == 1 % one decade per point
  1345.                     StrFile{end+1}='% x-Minor Ticks:';
  1346.                     for ii=1:length(fig.XTick)-1, % x=const
  1347.                         for jj=1:length(subPoints_log),
  1348.                             if fig.XTick(ii)+subPoints_log(jj) <= fig.XLim(2),
  1349.                                 StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),',',num2str(fig.YLim(1)+TickMinorLengthY,globals.FloatingPointFormat),')'];
  1350.                             end
  1351.                         end
  1352.                     end
  1353.                 end
  1354.             end
  1355.         end
  1356.         if strcmp(fig.YMinorTick,'on') && fig.yLog==1 % YMinorTick and log
  1357.             if length(fig.YTick)>1, % at least two points
  1358.                 if fig.YTick(2)-fig.YTick(1) == 1 % one decade per point
  1359.                     StrFile{end+1}='% y-Minor Ticks:';
  1360.                     for ii=1:length(fig.YTick)-1, % y=const
  1361.                         for jj=1:length(subPoints_log),
  1362.                             if fig.YTick(ii)+subPoints_log(jj) <= fig.YLim(2),
  1363.                                 StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),')(',num2str(fig.XLim(1)+TickMinorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick(ii)+subPoints_log(jj),globals.FloatingPointFormat),')'];
  1364.                             end
  1365.                         end
  1366.                     end
  1367.                 end
  1368.             end
  1369.         end
  1370.         if ~isempty(ahSecond), % additional right side
  1371.             subPoints_log2=yAxisCenversionFac*subPoints_log;
  1372.             if strcmp(fig.YMinorTick2,'on') && fig.yLog2==1 % YMinorTick and log
  1373.                 if length(fig.YTick2)>1, % at least two points
  1374.                     if fig.YTick2(2)-fig.YTick2(1) == 1 % one decade per point
  1375.                         StrFile{end+1}='% y-Minor Ticks Second Axis:';
  1376.                         for ii=1:length(fig.YTick2)-1, % y=const
  1377.                             for jj=1:length(subPoints_log),
  1378.                                 StrFile{end+1}=['\psline[linewidth=\AxesLineWidth,linecolor=GridColor](',num2str(fig.XLim(2)-TickMinorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick2Tex(ii)+subPoints_log2(jj),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YTick2Tex(ii)+subPoints_log2(jj),globals.FloatingPointFormat),')'];
  1379.                             end
  1380.                         end
  1381.                     end
  1382.                 end
  1383.             end
  1384.         end
  1385.        
  1386.        
  1387.        
  1388.     end
  1389.    
  1390.     % draw labels
  1391.     StrFile{end+1}='';
  1392.     StrFile{end+1}=['{ ',globals.FontSizeTickLabels,' % FontSizeTickLabels'];
  1393.     StrFile{end+1}='% Draw x-Labels: ----';
  1394.     for ii=1:length(fig.XTick),
  1395.         StrFile{end+1}=['\rput[t](',num2str(fig.XTick(ii),globals.FloatingPointFormat),',',num2str(fig.YLim(1)-TickMajorLengthY,globals.FloatingPointFormat),'){',fig.XTickLabelTex{ii},'}'];
  1396.     end
  1397.     StrFile{end+1}='% Draw y-Labels: ----';
  1398.     for ii=1:length(fig.YTick),
  1399.         StrFile{end+1}=['\rput[r](',num2str(fig.XLim(1)-TickMajorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick(ii),globals.FloatingPointFormat),'){',fig.YTickLabelTex{ii},'}'];
  1400.     end
  1401.     if ~isempty(ahSecond), % additional right side
  1402.         StrFile{end+1}='% Draw y-Labels Second Axis: ----';
  1403.         for ii=1:length(fig.YTick2),
  1404.             StrFile{end+1}=['\rput[l](',num2str(fig.XLim(2)+TickMajorLengthX,globals.FloatingPointFormat),',',num2str(fig.YTick2Tex(ii),globals.FloatingPointFormat),'){',fig.YTickLabelTex2{ii},'}'];
  1405.         end
  1406.     end
  1407.     StrFile{end+1} = '} % End FontSizeTickLabels'; % end of     FontSizeXYlabel
  1408.    
  1409.  
  1410.     if strcmp(fig.AxesVisible,'on') && ~globals.AxesBoxEnd, % draw only in this case
  1411.         StrFile{end+1}='';
  1412.         StrFile{end+1}='% Draw Axes: ----';
  1413.         if strcmp(fig.Box,'off'),
  1414.             % only left bottom
  1415.             StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')'];
  1416.             StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1417.             if ~isempty(ahSecond), % additional right
  1418.                 StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1419.             end
  1420.         else
  1421.             tmpstr = '\psframe[linewidth=\AxesLineWidth,dimen=middle](#1#,#2#)(#3#,#4#)';
  1422.             StrFile{end+1}=strfill(tmpstr,{fig.XLim(1),fig.YLim(1),fig.XLim(2),fig.YLim(2)});
  1423.         end
  1424.     end
  1425.    
  1426.    
  1427.     %%
  1428.    
  1429.     % LABELS FOR X- AND Y- AXIS AND TITLE
  1430.    
  1431.     % XLabel
  1432.     wrstr={};
  1433.     xlh = get(fig.axh,'XLabel');
  1434.     linestr = '\rput[b](#1#,#2#){';
  1435.     xlabelX = sum(fig.XLim)/2;
  1436.     xlabelY = figy1; % align at bottom
  1437.     linestr = strfill(linestr,{xlabelX,xlabelY});
  1438.     wrstr = [wrstr,{linestr}];
  1439.     wrstr = [wrstr,{'\begin{tabular}{c}'}];
  1440.     xlab = get(xlh,'String');
  1441.     StrFile{end+1}=''; % add empty line
  1442.     StrFile{end+1}=['{ ',globals.FontSizeXYlabel,' % FontSizeXYlabel'];
  1443.     if xlab
  1444.         StrFile{end+1}='% x-Label: ----';
  1445.         for labstr = xlab'
  1446.             wrstr = [wrstr,{strcat((labstr(:,1))','\\')}];
  1447.         end;
  1448.         wrstr = [wrstr,{'\end{tabular}','}'}];
  1449.         for ii=1:length(wrstr),
  1450.             StrFile{end+1}=wrstr{ii};
  1451.         end
  1452.     end;
  1453.    
  1454.     % YLabel
  1455.     wrstr={};
  1456.     ylh = get(fig.axh,'YLabel');
  1457.     linestr = '\rput[t]{90}(#1#,#2#){';
  1458.     ylabelX = figx1; % align left
  1459.     ylabelY = sum(fig.YLim)/2;
  1460.     linestr = strfill(linestr,{ylabelX,ylabelY});
  1461.     wrstr = [wrstr,{linestr}];
  1462.     wrstr = [wrstr,{'\begin{tabular}{c}'}];
  1463.     ylab = get(ylh,'String');
  1464.     if ylab;
  1465.         StrFile{end+1}=''; % add empty line
  1466.         StrFile{end+1}='% y-Label: ----';
  1467.         for labstr = ylab'
  1468.             wrstr = [wrstr,{strcat((labstr(:,1))','\\')}];
  1469.         end;
  1470.         wrstr = [wrstr,{'\end{tabular}'},{'}'}];
  1471.         for ii=1:length(wrstr),
  1472.             StrFile{end+1}=wrstr{ii};
  1473.         end
  1474.     end;
  1475.    
  1476.     % Second YLabel
  1477.     if ~isempty(ahSecond), % additional right side
  1478.         wrstr={};
  1479.         ylh = get(fig.axh2,'YLabel');
  1480.         linestr = '\rput[b]{90}(#1#,#2#){';
  1481.         ylabelX = figx2; % align right
  1482.         ylabelY = sum(fig.YLim)/2;
  1483.         linestr = strfill(linestr,{ylabelX,ylabelY});
  1484.         wrstr = [wrstr,{linestr}];
  1485.         wrstr = [wrstr,{'\begin{tabular}{c}'}];
  1486.         ylab = get(ylh,'String');
  1487.         if ylab;
  1488.             StrFile{end+1}=''; % add empty line
  1489.             StrFile{end+1}='% y-Label Second Axis: ----';
  1490.             for labstr = ylab'
  1491.                 wrstr = [wrstr,{strcat((labstr(:,1))','\\')}];
  1492.             end;
  1493.             wrstr = [wrstr,{'\end{tabular}'},{'}'}];
  1494.             for ii=1:length(wrstr),
  1495.                 StrFile{end+1}=wrstr{ii};
  1496.             end
  1497.         end
  1498.     end
  1499.    
  1500.     % Title
  1501.     th = get(fig.axh,'Title');
  1502.     wrstr={};
  1503.     linestr = '\rput[t](#1#,#2#){';
  1504.     titleX = sum(fig.XLim)/2;
  1505.     titleY = figy2; % align at top
  1506.     linestr = strfill(linestr,{titleX,titleY});
  1507.     wrstr = [wrstr,{linestr}];
  1508.     wrstr = [wrstr,{'\begin{tabular}{c}'}];
  1509.     titlab = get(th,'String');
  1510.     if titlab
  1511.         StrFile{end+1}=''; % add empty line
  1512.         StrFile{end+1}='% Title: ----';
  1513.         for labstr = titlab'
  1514.             wrstr = [wrstr,{strcat((labstr(:,1))','\\')}];
  1515.         end;
  1516.         wrstr = [wrstr,{'\end{tabular}'},{'}'}];
  1517.         for ii=1:length(wrstr),
  1518.             StrFile{end+1}=wrstr{ii};
  1519.         end
  1520.     end;
  1521.    
  1522.     StrFile{end+1} = '} % End FontSizeXYlabel'; % end of     FontSizeXYlabel
  1523.  
  1524. end % axes visible
  1525.  
  1526.  
  1527. if ischar(globals.AxesLineWidth)
  1528.     StrFile={['\providelength{\AxesLineWidth}       \setlength{\AxesLineWidth}{',globals.AxesLineWidth,'}%'],StrFile{1:end}};
  1529. else
  1530.     StrFile={['\providelength{\AxesLineWidth}       \setlength{\AxesLineWidth}{',num2str(globals.AxesLineWidth),'pt}%'],StrFile{1:end}};
  1531. end
  1532. StrFile={'% Global Parameters that can be changed:',StrFile{1:end}};
  1533.  
  1534. %%
  1535.  
  1536. % WRITE DATA TO FILE
  1537.  
  1538. lshandles = get(fig.axh,'Children');
  1539. lshandles = double(find(handle(lshandles),'-class','graph2d.lineseries'));
  1540. lshandles = flipud(lshandles); % flip lshandles in order to get the correct plot order
  1541. kk = 0;
  1542. for lsh=lshandles'; % scan all data lines
  1543.     kk = kk + 1;
  1544.    
  1545.     xd = get(lsh,'XData');
  1546.     yd = get(lsh,'YData');
  1547.    
  1548.     if length(xd)==1, % a single point, double for visualization
  1549.         xd=[xd, xd]; yd=[yd, yd];
  1550.     end
  1551.    
  1552.     % cut data that are out of bounds and append them as extra lines:
  1553.     [Pcutt, Psnipp] = cut_data (xd, yd, fig.XLim, fig.YLim);
  1554.  
  1555.    
  1556.     xd_cut = {};
  1557.     yd_cut = {};
  1558.     mark_on = [];
  1559.    
  1560.     % append snippets
  1561.     for ii = 1 : length(Psnipp)
  1562.         xd_cut{ii} = Psnipp{ii}(:,1);
  1563.         yd_cut{ii} = Psnipp{ii}(:,2);
  1564.         mark_on(ii) = 0;
  1565.     end
  1566.    
  1567.     % append valid lines
  1568.     for ii = 1 : length(Pcutt)        
  1569.         if size(Pcutt{ii}, 1) == 1,  % a single point, double for visualization
  1570.             xd_cut{end+1} = [Pcutt{ii}(:,1); Pcutt{ii}(:,1)];
  1571.             yd_cut{end+1} = [Pcutt{ii}(:,2); Pcutt{ii}(:,2)];
  1572.         else
  1573.             xd_cut{end+1} = Pcutt{ii}(:,1);
  1574.             yd_cut{end+1} = Pcutt{ii}(:,2);            
  1575.         end
  1576.         mark_on(end+1) = 1;
  1577.     end
  1578.  
  1579.     % copy back:
  1580.     xd = xd_cut;
  1581.     yd = yd_cut;
  1582.      
  1583.     % get the markers
  1584.     markerStr=convert_Marker(get(lsh,'Marker'));
  1585.     markerStr=markerStr{1}; % no cell array
  1586.    
  1587.  
  1588.     % get the linestyle
  1589.     linestyle = convert_lineStyle(get(lsh,'LineStyle'));
  1590.     linestyle = linestyle{1}; % no cell array
  1591.    
  1592.  
  1593.     % check for patch
  1594.     if isempty(fig.FaceColor{kk}), % line, no patch
  1595.         isPatch = false;
  1596.         StrFile{end+1}='';
  1597.         cname   = ['color',num2str(lsh)];
  1598.         cnameFC = [];
  1599.         colstr  = ['\newrgbcolor{',cname,'}{',num2str(get (lsh,'Color')),'}'];
  1600.         StrFile{end+1}='% New Line DATA: ----';
  1601.         StrFile{end+1}=colstr;
  1602.        
  1603.     else
  1604.         isPatch = true;
  1605.        
  1606.         % put all snippets together in order to obtain a single cut patch again
  1607.         if ~isempty(xd),
  1608.             xdd = xd{1};
  1609.             ydd = yd{1};
  1610.             for jj=2:length(xd)-1, % all cut data are written
  1611.                 xdd = [xdd; xd{jj}];
  1612.                 ydd = [ydd; yd{jj}]; % save current cut data
  1613.             end
  1614.             xd = {xdd};
  1615.             yd = {ydd};
  1616.  
  1617.             StrFile{end+1}='';
  1618.             Fcol = fig.FaceColor{kk};
  1619.             Lcol = fig.LineColor{kk};
  1620.             cname   = ['Lcolor',num2str(lsh)];
  1621.             cnameFC = ['Fcolor',num2str(lsh)];
  1622.             StrFile{end+1}='% New Patch DATA: ----';
  1623.             colstr  = ['\newrgbcolor{',cname,'}{',num2str(fig.LineColor{kk}),'}'];
  1624.             StrFile{end+1}=colstr;
  1625.             colstr  = ['\newrgbcolor{',cnameFC,'}{',num2str(fig.FaceColor{kk}),'}'];
  1626.             StrFile{end+1}=colstr;
  1627.  
  1628.         end
  1629.  
  1630.     end
  1631.    
  1632.     % write data
  1633.     for jj=1:length(xd), % all cut data are written
  1634.         xdd=xd{jj}'; ydd=yd{jj}'; % save current cut data
  1635.        
  1636.         if length (xdd) > 1, % at least two points
  1637.            
  1638.             % reduce number of points for the current line
  1639.             if strcmp(markerStr,'none'), % do NOT reduce for lines with markers
  1640.                 xydata=reduce_line([xdd;ydd],globals.PointReduceFactor);
  1641.                 xdd=xydata(1,:);
  1642.                 ydd=xydata(2,:);
  1643.             end
  1644.            
  1645.             if isPatch % in this case patches are plotted
  1646.                
  1647.                 StrFile{end+1}='\savedata{\mydata}[{';
  1648.                 tmpstr=''; % init
  1649.                 for ii=1:length(xdd),
  1650.                     tmpstr = [tmpstr,'{',num2str(xdd(ii),globals.FloatingPointFormat),',',num2str(ydd(ii),globals.FloatingPointFormat),'},'];
  1651.                     if mod(ii,5)==0, % new line all 5 data pair
  1652.                         StrFile{end+1}=tmpstr;
  1653.                         tmpstr='';
  1654.                     end
  1655.                 end
  1656.                 if not(isempty(tmpstr)), % last line
  1657.                     tmpstr(end)=''; % delete last ','
  1658.                     StrFile{end+1}=tmpstr;
  1659.                 end
  1660.                 StrFile{end+1}='}]';
  1661.                                
  1662.                 tmpstr = ['\dataplot[fillstyle=solid,fillcolor=#2#,plotstyle=line,linestyle=#1#,linewidth=\EdgeLineWidth,linecolor=#3#]{\mydata}'];
  1663.                 wrstr = strfill(tmpstr,{linestyle,cnameFC,cname});
  1664.                 StrFile{end+1}=wrstr;
  1665.                
  1666.             else % line
  1667.                 if strcmp(markerStr,'none'), % do not show markers
  1668.                     tmpstr = ['\psline[plotstyle=line,linejoin=1,linestyle=#1#,linewidth=\LineWidth,linecolor=#2#]'];
  1669.                 else                         % show markers
  1670.                     if mark_on(jj),
  1671.                         showpoints = 'true';
  1672.                     else
  1673.                         showpoints = 'false';
  1674.                     end
  1675.                     tmpstr = ['\psline[plotstyle=line,linejoin=1,showpoints=',showpoints,',dotstyle=',markerStr,',dotsize=\MarkerSize,linestyle=#1#,linewidth=\LineWidth,linecolor=#2#]'];
  1676.                 end
  1677.                 wrstr = strfill(tmpstr,{linestyle,cname});
  1678.                 StrFile{end+1}=wrstr;
  1679.                
  1680.                 tmpstr='';
  1681.                 for ii=1:length(xdd),
  1682.                     tmpstr = [tmpstr,'(',num2str(xdd(ii),globals.FloatingPointFormat),',',num2str(ydd(ii),globals.FloatingPointFormat),')'];
  1683.                     if mod(ii,5)==0, % new line all 5 data pair
  1684.                         StrFile{end+1}=tmpstr;
  1685.                         tmpstr='';
  1686.                     end
  1687.                 end
  1688.                 if not(isempty(tmpstr)), % last line
  1689.                     StrFile{end+1}=tmpstr;
  1690.                 end
  1691.                
  1692.                
  1693.             end
  1694.            
  1695.         end
  1696.     end
  1697. end
  1698.  
  1699. %%
  1700.  
  1701. % Axes Box
  1702.  
  1703. if strcmp(fig.AxesVisible,'on') && globals.AxesBoxEnd, % draw only in this case
  1704.     StrFile{end+1}='';
  1705.     StrFile{end+1}='% Draw Axes: ----';
  1706.     if strcmp(fig.Box,'off'),
  1707.         % only left bottom
  1708.         StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')'];
  1709.         StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(1),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1710.         if ~isempty(ahSecond), % additional right
  1711.             StrFile{end+1}=['\psline[linewidth=\AxesLineWidth](',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(1),globals.FloatingPointFormat),')(',num2str(fig.XLim(2),globals.FloatingPointFormat),',',num2str(fig.YLim(2),globals.FloatingPointFormat),')'];
  1712.         end
  1713.     else
  1714.         tmpstr = '\psframe[linewidth=\AxesLineWidth,dimen=middle](#1#,#2#)(#3#,#4#)';
  1715.         StrFile{end+1}=strfill(tmpstr,{fig.XLim(1),fig.YLim(1),fig.XLim(2),fig.YLim(2)});
  1716.     end
  1717. end
  1718.  
  1719.  
  1720.  
  1721. %%
  1722.  
  1723. % LEGEND
  1724. [legh,object_h,plot_h,text_strings] = legend(fig.axh); % get legend information
  1725. if ~isempty(legh)
  1726.     ts=globals.LegendBoxTeXcode; % first line for the legend box
  1727.     % ts={'\psshadowbox[framesep=0pt]{\psframebox*{\begin{tabular}{l}'};
  1728.     rowstr='\Rnode{a#1#}{\hspace*{0.0ex}} \hspace*{0.7cm} \Rnode{a#2#}{~~#3#} \\';
  1729.     llstr={};
  1730.     if numPatches > length(plot_h),
  1731.         kstart = 1;
  1732.         nPatchs = 0;
  1733.     else
  1734.         kstart  = numPatches+1;
  1735.         nPatchs = numPatches;
  1736.     end
  1737.     for k=kstart:length(plot_h)% do not account for the patches at the beginning
  1738.         markerStr=convert_Marker(get(plot_h(k),'Marker'));
  1739.         markerStr=markerStr{1}; % no cell array
  1740.         if strcmp(markerStr,'none'), % do not show markers
  1741.             ncstr='\ncline[linestyle=#1#,linewidth=\LineWidth,linecolor=#4#]{a#2#}{a#3#}';
  1742.         else
  1743.             ncstr=['\ncline[linestyle=#1#,linewidth=\LineWidth,linecolor=#4#]{a#2#}{a#3#} \ncput{\psdot[dotstyle=',markerStr,',dotsize=\MarkerSize,linecolor=#4#]}'];
  1744.         end
  1745.         tabstr = strfill(rowstr,{num2str(2*k-1),num2str(2*k),text_strings(k-nPatchs)});
  1746.         ts=[ts,tabstr];
  1747.         linestyle = convert_lineStyle(get(plot_h(k),'LineStyle'));
  1748.         linestyle = linestyle{1}; % convert from cell to chars
  1749.         cname=['color',num2str(plot_h(k))];
  1750.         leglinestr = strfill(ncstr,{linestyle,num2str(2*k-1),num2str(2*k),cname});
  1751.         llstr = [llstr,{leglinestr}];
  1752.     end;
  1753.     ts=[ts,{'\end{tabular}}'}];
  1754.    
  1755.     % legend's position
  1756.     set(legend_org,'Units','normalized')
  1757.     lp = get(legend_org,'Position'); % position normalized
  1758.     % convert relative figure positions to x-and y-values
  1759.     set(ah,'Units','normalized');
  1760.     pos=get(ah,'Position');
  1761.     XY1=pos(1:2); Width=pos(3:4);
  1762.     legendposX=((lp(1)+lp(3)/2)-XY1(1))./Width(1)*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1); % normalized axes units
  1763.     legendposY=((lp(2)+lp(4)/2)-XY1(2))./Width(2)*(fig.YLim(2)-fig.YLim(1))+fig.YLim(1);
  1764.    
  1765.     switch get(legh,'Location'),
  1766.         case 'NorthWest'
  1767.             tmpstr = '\rput[tl](#1#,#2#){%';
  1768.             legendposX = fig.XLim(1)+TickMajorLengthX*globals.LegendOffsetFac;
  1769.             legendposY = fig.YLim(2)-TickMajorLengthY*globals.LegendOffsetFac;
  1770.         case 'SouthWest'
  1771.             tmpstr = '\rput[bl](#1#,#2#){%';
  1772.             legendposX = fig.XLim(1)+TickMajorLengthX*globals.LegendOffsetFac;
  1773.             legendposY = fig.YLim(1)+TickMajorLengthY*globals.LegendOffsetFac;
  1774.         case 'SouthEast'
  1775.             tmpstr = '\rput[br](#1#,#2#){%';
  1776.             legendposX = fig.XLim(2)-TickMajorLengthX*globals.LegendOffsetFac;
  1777.             legendposY = fig.YLim(1)+TickMajorLengthY*globals.LegendOffsetFac;
  1778.         case 'NorthEast'
  1779.             tmpstr = '\rput[tr](#1#,#2#){%';
  1780.             legendposX = fig.XLim(2)-TickMajorLengthX*globals.LegendOffsetFac;
  1781.             legendposY = fig.YLim(2)-TickMajorLengthY*globals.LegendOffsetFac;
  1782.         case 'West'
  1783.             tmpstr = '\rput[l](#1#,#2#){%';
  1784.             legendposX = fig.XLim(1)+TickMajorLengthX*globals.LegendOffsetFac;
  1785.             legendposY = (fig.YLim(1) + fig.YLim(2)) / 2;
  1786.         case 'South'
  1787.             tmpstr = '\rput[b](#1#,#2#){%';
  1788.             legendposX = (fig.XLim(1) + fig.XLim(2)) / 2;
  1789.             legendposY = fig.YLim(1)+TickMajorLengthY*globals.LegendOffsetFac;
  1790.         case 'East'
  1791.             tmpstr = '\rput[r](#1#,#2#){%';
  1792.             legendposX = fig.XLim(2)-TickMajorLengthX*globals.LegendOffsetFac;
  1793.             legendposY = (fig.YLim(1) + fig.YLim(2)) / 2;
  1794.         case 'North'
  1795.             tmpstr = '\rput[t](#1#,#2#){%';
  1796.             legendposX = (fig.XLim(1) + fig.XLim(2)) / 2;
  1797.             legendposY = fig.YLim(2)-TickMajorLengthY*globals.LegendOffsetFac;
  1798.         case 'NorthEastOutside'
  1799.             tmpstr = '\rput[lt](#1#,#2#){%';
  1800.             legendposX = fig.XLim(2)+TickMajorLengthX*globals.LegendOffsetFac;
  1801.             legendposY = fig.YLim(2);
  1802.         case 'EastOutside'
  1803.             tmpstr = '\rput[l](#1#,#2#){%';
  1804.             legendposX = fig.XLim(2)+TickMajorLengthX*globals.LegendOffsetFac;
  1805.             legendposY = (fig.YLim(1) + fig.YLim(2)) / 2;
  1806.         case 'SouthEastOutside'
  1807.             tmpstr = '\rput[lb](#1#,#2#){%';
  1808.             legendposX = fig.XLim(2)+TickMajorLengthX*globals.LegendOffsetFac;
  1809.             legendposY = fig.YLim(1);
  1810.         case 'NorthWestOutside'
  1811.             tmpstr = '\rput[rt](#1#,#2#){%';
  1812.             legendposX = figx1-TickMajorLengthX*globals.LegendOffsetFac;
  1813.             legendposY = fig.YLim(2);
  1814.         case 'WestOutside'
  1815.             tmpstr = '\rput[r](#1#,#2#){%';
  1816.             legendposX = figx1-TickMajorLengthX*globals.LegendOffsetFac;
  1817.             legendposY = (fig.YLim(1) + fig.YLim(2)) / 2;
  1818.         case 'SouthWestOutside'
  1819.             tmpstr = '\rput[rb](#1#,#2#){%';
  1820.             legendposX = figx1-TickMajorLengthX*globals.LegendOffsetFac;
  1821.             legendposY = fig.YLim(1);
  1822.         otherwise
  1823.             tmpstr = '\rput(#1#,#2#){%';
  1824.     end
  1825.     wrstr = strfill(tmpstr,{legendposX,legendposY});
  1826.     StrFile{end+1}=''; StrFile{end+1}='% Legend: ----';
  1827.     StrFile{end+1}=['{ ',globals.FontSizeLegend,' % FontSizeLegend'];
  1828.     StrFile{end+1}=wrstr;
  1829.    
  1830.     tmpstr2 = [ts,llstr,{'}%'},{'}%'}];
  1831.     for ii=1:length(tmpstr2)
  1832.         StrFile{end+1}=tmpstr2{ii};
  1833.     end;
  1834.     StrFile{end+1} = '} % End FontSizeLegend'; % end of     FontSizeLegend
  1835.    
  1836. end;
  1837.  
  1838. %%
  1839.  
  1840. % Colorbar
  1841. if ~isempty(ColBar),
  1842.    
  1843.     if strcmp(ColBar.Location, 'EastOutside'), % only location supported right now
  1844.        
  1845.         StrFile{end+1}=''; StrFile{end+1}='% Colorbar: ----';
  1846.        
  1847.         % Position of the colorbar
  1848.        
  1849.         lp = ColBar.Position; % position normalized
  1850.         % convert relative figure positions to x-and y-values
  1851.         set(ah,'Units','normalized');
  1852.         pos=get(ah,'Position');
  1853.         XY1=pos(1:2); Width=pos(3:4);
  1854.         ColBarPosYB=fig.YLim(1);
  1855.         ColBarPosYT=fig.YLim(2);
  1856.         if isempty(globals.ColorBarWidth_cm)
  1857.            
  1858.             % (FROM MATLAB)
  1859.             ColBarPosXL=((lp(1))      -XY1(1))./Width(1)*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1); % normalized axes units
  1860.             ColBarPosXR=((lp(1)+lp(3))-XY1(1))./Width(1)*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1);
  1861.             % ColBarPosYB=((lp(2))      -XY1(2))./Width(2)*(fig.YLim(2)-fig.YLim(1))+fig.YLim(1);
  1862.             % ColBarPosYT=((lp(2)+lp(4))-XY1(2))./Width(2)*(fig.YLim(2)-fig.YLim(1))+fig.YLim(1);
  1863.            
  1864.         elseif length(globals.ColorBarWidth_cm) == 1, % scalar width
  1865.        
  1866.             ColBarPosXL=((lp(1))-XY1(1))./Width(1)*(fig.XLim(2)-fig.XLim(1))+fig.XLim(1); % normalized axes units
  1867.             ColBarPosXR = ColBarPosXL+globals.ColorBarWidth_cm/globals.plotwidth*DeltaXLim;
  1868.            
  1869.         elseif length(globals.ColorBarWidth_cm) == 2, % [width, offset]
  1870.            
  1871.             ColBarPosXL = fig.XLim(2) + globals.ColorBarWidth_cm(2)/globals.plotwidth*DeltaXLim; % normalized axes units
  1872.             ColBarPosXR = ColBarPosXL + globals.ColorBarWidth_cm(1)/globals.plotwidth*DeltaXLim;
  1873.            
  1874.         else
  1875.             error('Wrong input format of globals.ColorBarWidth_cm!')
  1876.         end
  1877.        
  1878.         cmap = ColBar.cmap;
  1879.        
  1880.         % Draw all color patches
  1881.         numColPatches = ColBar.CLim(2) - ColBar.CLim(1);
  1882.         % numColPatches = size(cmap, 1) % default is 64
  1883.         dY = (ColBarPosYT - ColBarPosYB) / numColPatches;
  1884.         for ii = 1 : numColPatches,
  1885.             randName = num2str(rand,8); % random name
  1886.             cname = ['colB',num2str(ii),'_',randName(3:6)];
  1887.             StrFile{end+1} = ['\newrgbcolor{',cname,'}{', ...
  1888.                 num2str(cmap(ii,1)),' ', ...
  1889.                 num2str(cmap(ii,2)),' ', ...
  1890.                 num2str(cmap(ii,3)),'}'];
  1891.             tmpstr = '\psframe[linewidth=0.1pt,linestyle=solid,linecolor=#1#,fillstyle=solid,fillcolor=#1#,dimen=middle](#2#,#3#)(#4#,#5#)';
  1892.             StrFile{end+1}=strfill(tmpstr,{cname, ...
  1893.                 ColBarPosXL,ColBarPosYB+(ii-1)*dY,ColBarPosXR,ColBarPosYB+ii*dY});
  1894.         end
  1895.         % Draw border
  1896.         tmpstr = '\pspolygon[linewidth=\AxesLineWidth](#1#,#2#)(#3#,#2#)(#3#,#4#)(#1#,#4#)(#1#,#2#)';
  1897.         StrFile{end+1}=strfill(tmpstr,{ColBarPosXL,ColBarPosYB,ColBarPosXR,ColBarPosYT});
  1898.        
  1899.        
  1900.         % Convert positions of ticks
  1901.         numTicks = length(ColBar.YTick);
  1902.         for ii = 1 : numTicks,
  1903.             Yact(ii) = ColBarPosYB + (ColBar.YTick(ii) - ColBar.YLim(1)) * ...
  1904.                 (ColBarPosYT - ColBarPosYB) / (ColBar.YLim(2) - ColBar.YLim(1));
  1905.         end
  1906.        
  1907.         % draw ticks
  1908.         TickColor = ColBar.YColor;
  1909.         randName = num2str(rand,8); % random name
  1910.         TickColorName = ['ColBarTickCol_',randName(3:6)];
  1911.         StrFile{end+1}='';
  1912.         StrFile{end+1}='% Draw Colorbar y-Ticks: ----';
  1913.         tmpstr = '\newrgbcolor{#1#}{#2# #3# #4#}';
  1914.         StrFile{end+1}=strfill(tmpstr,{ ...
  1915.             TickColorName, TickColor(1), TickColor(2), TickColor(3)});
  1916.         ColBarWidth = ColBarPosXR - ColBarPosXL;
  1917.         for ii=1:numTicks, % y=const
  1918.             % left tick:
  1919.             tmpstr = '\psline[linewidth=\AxesLineWidth,linecolor=#4#](#1#,#2#)(#3#,#2#)';
  1920.             StrFile{end+1}=strfill(tmpstr, ...
  1921.                 {ColBarPosXL,Yact(ii),ColBarPosXL+ColBarWidth/6, ...
  1922.                 TickColorName});
  1923.             % right tick:
  1924.             tmpstr = '\psline[linewidth=\AxesLineWidth,linecolor=#4#](#1#,#2#)(#3#,#2#)';
  1925.             StrFile{end+1}=strfill(tmpstr, ...
  1926.                 {ColBarPosXR,Yact(ii),ColBarPosXR-ColBarWidth/6, ...
  1927.                 TickColorName});
  1928.         end
  1929.        
  1930.         % draw labels
  1931.         StrFile{end+1}='';
  1932.         StrFile{end+1}=['{ ',globals.FontSizeTickLabels,' % FontSizeTickLabels'];
  1933.         StrFile{end+1}='% Draw Colorbar y-Labels: ----';
  1934.         labels_out = convert_TickLabels2Cell (ColBar.YTick, ColBar.YTickLabel);
  1935.         for ii=1:numTicks,
  1936.             tmpstr = '\rput[l](#1#,#2#){$#3#$}';
  1937.             StrFile{end+1}=strfill(tmpstr, ...
  1938.                 {ColBarPosXR+TickMajorLengthX,Yact(ii),labels_out{ii}});
  1939.         end
  1940.         StrFile{end+1} = '} % End FontSizeTickLabels'; % end of     FontSizeXYlabel
  1941.        
  1942.        
  1943.         % drax y-label
  1944.         StrFile{end+1}=''; % add empty line
  1945.         StrFile{end+1}=['{ ',globals.FontSizeXYlabel,' % FontSizeXYlabel'];
  1946.         wrstr={};
  1947.         linestr = '\rput[b]{90}(#1#,#2#){';
  1948.         % align right and use the same offset the y label on the left hand
  1949.         % side:
  1950.         % ColBarPosXR = ColBarPosXL + globals.ColorBarWidth_cm(1)/globals.plotwidth*DeltaXLim;
  1951.        
  1952.         % test if right tight inset is larger than left tight inset +
  1953.         % colorbar width
  1954.         if globals.tightInset_cm(3) > ...
  1955.                 (globals.tightInset_cm(1) + sum(globals.ColorBarWidth_cm)),
  1956.             ylabelX = figx2; % right
  1957.         else
  1958.             ylabelX = ColBarPosXR + globals.tightInset_cm(1)/globals.plotwidth*DeltaXLim;
  1959.         end
  1960.         ylabelY = sum(fig.YLim)/2;
  1961.         linestr = strfill(linestr,{ylabelX,ylabelY});
  1962.         wrstr = [wrstr,{linestr}];
  1963.         wrstr = [wrstr,{'\begin{tabular}{c}'}];
  1964.         ylab = get(ColBar.YLabel,'String');
  1965.         if ylab;
  1966.             StrFile{end+1}='% y-Label Colorbar: ----';
  1967.             for labstr = ylab'
  1968.                 wrstr = [wrstr,{strcat((labstr(:,1))','\\')}];
  1969.             end;
  1970.             wrstr = [wrstr,{'\end{tabular}'},{'}'}];
  1971.             for ii=1:length(wrstr),
  1972.                 StrFile{end+1}=wrstr{ii};
  1973.             end
  1974.         end
  1975.         StrFile{end+1} = '} % End FontSizeXYlabel'; % end of  FontSizeXYlabel
  1976.        
  1977.        
  1978.        
  1979.     else
  1980.        
  1981.         warning('The only supported location of the Colorbar is EastOutside!')
  1982.        
  1983.     end
  1984.    
  1985. end
  1986.  
  1987.  
  1988.  
  1989.  
  1990.  
  1991. %%
  1992.  
  1993. % Textarrows
  1994. if ~isempty(anhar),
  1995.    
  1996.     if ~ischar (globals.TextArrowLineWidth)
  1997.         TextArrowLineWidth = [num2str(globals.TextArrowLineWidth),'pt'];
  1998.     else
  1999.         TextArrowLineWidth = globals.TextArrowLineWidth;
  2000.     end
  2001.    
  2002.     StrFile{end+1}='';
  2003.     StrFile{end+1}=['{ ',globals.FontSizeAnnotations,' % FontSizeAnnotations'];
  2004.     StrFile{end+1}='% Text Arrows: ----';
  2005.     for ii=1:length(fig.TextarrowsStr),
  2006.         wrstr ={}; % init
  2007.         wrstr = [wrstr,['% Number ',num2str(ii),':']];
  2008.         cname=['color',num2str(anhar(ii))]; % name is random, just num2str of the handle
  2009.         colstr=['\newrgbcolor{',cname,'}{',num2str(fig.TextarrowsColor{ii}),'}'];
  2010.         wrstr = [wrstr,colstr];
  2011.         annostr = fig.TextarrowsStr{ii};        
  2012.         annoX = fig.TextarrowsX(ii,:);
  2013.         annoY = fig.TextarrowsY(ii,:);
  2014.         lstTA=convert_lineStyle(fig.TextarrowsLineStyle{ii});
  2015.         linestr = ['\psline[linestyle=',lstTA{1},',linewidth=', ...
  2016.             TextArrowLineWidth,',linecolor=#5#,arrowsize=1.5pt 3,arrowlength=2,arrowinset=0.3]{->}(#1#,#2#)(#3#,#4#)'];
  2017.         linestr = strfill(linestr,{annoX(1),annoY(1),annoX(2),annoY(2),cname});
  2018.         wrstr = [wrstr,linestr];
  2019.         if ~isempty(annostr), % do this only if a string is present
  2020.             linestr = '\uput{0pt}[#1#](#2#,#3#){%';
  2021.             linestr = strfill(linestr,{fig.TextarrowsRot(ii),annoX(1),annoY(1)});
  2022.             wrstr = [wrstr,linestr];
  2023.             if length(annostr)==1, % text is just one line, don't use a tabular
  2024.                 if globals.TextArrowTextColor==1, % adapt the color
  2025.                     linestr='\psframebox*[framesep=1pt]{\textcolor{#2#}{#1#}}}';
  2026.                     linestr = strfill(linestr,{annostr,cname});
  2027.                 else
  2028.                     linestr='\psframebox*[framesep=1pt]{#1#}}';
  2029.                     linestr = strfill(linestr,{annostr});
  2030.                 end
  2031.                 wrstr = [wrstr,linestr];
  2032.             else
  2033.                 if globals.TextArrowTextColor==1, % adapt the color
  2034.                     if strcmp(fig.TextarrowsHorizontalAlignment, 'left'),
  2035.                         al = 'l';
  2036.                     elseif strcmp(fig.TextarrowsHorizontalAlignment, 'right'),
  2037.                         al = 'r';
  2038.                     else
  2039.                         al = 'c';
  2040.                     end
  2041.                     linestr =['\psframebox*[framesep=1pt]{\textcolor{#1#}{\begin{tabular}{@{}',al,'@{}}'];
  2042.                     linestr = strfill(linestr,{cname});
  2043.                     endstr  =  ['\end{tabular}','}}}'];
  2044.                 else
  2045.                     linestr='\psframebox*[framesep=1pt]{\begin{tabular}{@{}c@{}}';
  2046.                     endstr =  ['\end{tabular}','}}'];
  2047.                 end
  2048.                 wrstr = [wrstr,linestr];
  2049.                 if ~iscell (annostr), annostr = {annostr}; end
  2050.                 for jj=1:length(annostr),
  2051.                     wrstr = [wrstr,strcat(annostr{jj},'\\[-0.3ex]')]; % [-0.3ex] negative space
  2052.                 end
  2053.                 wrstr = [wrstr,endstr];
  2054.             end
  2055.         end
  2056.         for ll=1:length(wrstr), % write everything to file
  2057.             StrFile{end+1}=wrstr{ll};
  2058.         end
  2059.     end
  2060.     StrFile{end+1} = '} % End FontSizeAnnotations'; % end of     FontSizeLegend
  2061. end
  2062.  
  2063.  
  2064. %%
  2065.  
  2066. % Text boxes
  2067. if ~isempty(anhtb),
  2068.    
  2069.     if ~ischar (globals.TextBoxLineWidth)
  2070.         TextBoxLineWidth = [num2str(globals.TextBoxLineWidth),'pt'];
  2071.     else
  2072.         TextBoxLineWidth = globals.TextBoxLineWidth;
  2073.     end
  2074.    
  2075.     StrFile{end+1}='';
  2076.     StrFile{end+1}=['{ ',globals.FontSizeAnnotations,' % FontSizeAnnotations'];
  2077.     StrFile{end+1}='% Text Boxes: ----';
  2078.     for ii=1:length(fig.TextBoxesStr),
  2079.        
  2080.         % convert current linestyle of the box
  2081.         lstyle = convert_lineStyle(fig.TextBoxesLineStyle{ii});
  2082.  
  2083.         wrstr ={}; % init
  2084.         wrstr = [wrstr,['% Number ',num2str(ii),':']];
  2085.         cname=['color',num2str(anhtb(ii))]; % name is random, just num2str of the handle
  2086.         colstr=['\newrgbcolor{',cname,'}{',num2str(fig.TextBoxesColor{ii}),'}'];
  2087.         wrstr = [wrstr,colstr];
  2088.         annostr = fig.TextBoxesStr{ii};
  2089.         annoX = fig.TextBoxesX(ii,:);
  2090.         annoY = fig.TextBoxesY(ii,:);
  2091.         linestr = '\uput{0pt}[0](#1#,#2#){%';
  2092.         linestr = strfill(linestr,{annoX(1),annoY(1)});
  2093.         wrstr = [wrstr,linestr];
  2094.          if length(annostr)==1, % text is just one line, don't use a tabular
  2095.             if globals.TextBoxTextColor==1, % adapt the color
  2096.                 linestr='\psframebox[framesep=1pt,fillstyle=solid,linestyle=#3#,linewidth=#4#]{\textcolor{#2#}{#1#}}}';
  2097.                 linestr = strfill(linestr,{annostr,cname,lstyle,TextBoxLineWidth});
  2098.             else
  2099.                 linestr='\psframebox[framesep=1pt,fillstyle=solid,linestyle=#2#,linewidth=#3#]{#1#}}';
  2100.                 linestr = strfill(linestr,{annostr,lstyle,TextBoxLineWidth});
  2101.             end
  2102.             wrstr = [wrstr,linestr];
  2103.         else
  2104.             if globals.TextBoxTextColor==1, % adapt the color
  2105.                 if strcmp(fig.TextBoxesHorizontalAlignment, 'left'),
  2106.                     al = 'l';
  2107.                 elseif strcmp(fig.TextBoxesHorizontalAlignment, 'right'),
  2108.                     al = 'r';
  2109.                 else
  2110.                     al = 'c';
  2111.                 end
  2112.                 linestr =['\psframebox[framesep=1pt,fillstyle=solid,linestyle=#2#,linewidth=#3#]{\textcolor{#1#}{\begin{tabular}{@{}',al,'@{}}'];
  2113.                 linestr = strfill(linestr,{cname,lstyle,TextBoxLineWidth});
  2114.                 endstr  =  ['\end{tabular}','}}}'];
  2115.             else
  2116.                 linestr='\psframebox[framesep=1pt,fillstyle=solid,linestyle=#1#,linewidth=#2#]{\begin{tabular}{@{}c@{}}';
  2117.                 linestr = strfill(linestr,{lstyle,TextBoxLineWidth});
  2118.                 endstr =  ['\end{tabular}','}}'];
  2119.             end
  2120.             wrstr = [wrstr,linestr];
  2121.             if ~iscell (annostr), annostr = {annostr}; end
  2122.             for jj=1:length(annostr),
  2123.                 wrstr = [wrstr,strcat(annostr{jj},'\\[-0.3ex]')]; % [-0.3ex] negative space
  2124.             end
  2125.             wrstr = [wrstr,endstr];
  2126.         end
  2127.         for ll=1:length(wrstr), % write everything to file
  2128.             StrFile{end+1}=wrstr{ll};
  2129.         end
  2130.     end
  2131.     StrFile{end+1} = '} % End FontSizeAnnotations'; % end of     FontSizeLegend
  2132. end
  2133.  
  2134.  
  2135. %%
  2136.  
  2137. % Convergence Triangle
  2138.  
  2139. % globals.TriangleOrder = []; % vector with orders that are shown, if empty, no convergence triangle
  2140. % globals.TriangleColor = [0.4 0.4 0.4]; % rgb vector
  2141. % globals.TriangleLxRel = 0.3;
  2142.  
  2143. if ~isempty(globals.TriangleOrder)
  2144.     ConTriposX = fig.XLim(1)+TickMajorLengthX*globals.LegendOffsetFac;
  2145.     ConTriposY = fig.YLim(1)+TickMajorLengthY*globals.LegendOffsetFac;
  2146.     bordersX   = fig.XLim;
  2147.     StartPoint = [ConTriposX, ConTriposY];
  2148.     numOrders  = length(globals.TriangleOrder);
  2149.     LineStyle  = 'solid';
  2150.     labelPos   = 0.2;
  2151.    
  2152.     StrFile{end+1}='';
  2153.     StrFile{end+1}=['{ ',globals.FontSizeAnnotations,' % FontSizeAnnotations'];
  2154.     StrFile{end+1}='% Convergence Triangle: ----';
  2155.     StrFile{end+1}=['\newrgbcolor{TriangleColor}{',num2str(globals.TriangleColor),'}'];
  2156.    
  2157.     % Nodes
  2158.     LB=StartPoint;
  2159.     RB=StartPoint+globals.TriangleLxRel*(bordersX(2)-bordersX(1))*[1 0];
  2160.     StrFile{end+1}=['\pnode(',num2str(LB(1)),',',num2str(LB(2)),'){LB}'];
  2161.     StrFile{end+1}=['\pnode(',num2str(RB(1)),',',num2str(RB(2)),'){RB}'];
  2162.     for ii = 1 : numOrders,
  2163.         LT{ii} = StartPoint + globals.TriangleLxRel * ...
  2164.             (bordersX(2)-bordersX(1)) * globals.TriangleOrder(ii) * [0 1];
  2165.         StrFile{end+1}=['\pnode(',num2str(LT{ii}(1)),',',num2str(LT{ii}(2)),'){LT',num2str(ii),'}'];
  2166.     end
  2167.    
  2168.     % Lines
  2169.     StrFile{end+1}=['\ncline[linecolor=TriangleColor,linestyle=',LineStyle,',linewidth=\AxesLineWidth,arrows=c-c]{LB}{RB}'];
  2170.     StrFile{end+1}=['\ncline[linecolor=TriangleColor,linestyle=',LineStyle,',linewidth=\AxesLineWidth,arrows=c-c]{LB}{LT',num2str(numOrders),'}'];
  2171.     for ii = 1 : numOrders,
  2172.         if ~isempty(globals.TriangleStr), % extra string
  2173.             str = globals.TriangleStr{ii};
  2174.         else
  2175.             str = sprintf('$%.2f$',globals.TriangleOrder(ii));
  2176.         end        
  2177.         StrFile{end+1}=['\ncline[linecolor=TriangleColor,linestyle=',LineStyle,',linewidth=\AxesLineWidth,arrows=c-c]{LT',num2str(ii),'}{RB}'];
  2178.         StrFile{end+1}=['\ncput[npos=',num2str(labelPos),']{\psframebox*[framesep=1pt]{',str,'}}'];
  2179.     end
  2180.    
  2181.     StrFile{end+1} = '} % End FontSizeAnnotations'; % end of     FontSizeLegend
  2182.    
  2183. end
  2184.  
  2185.  
  2186.  
  2187. %%
  2188.  
  2189. for ii = 1 : length(globals.AddCode) % append additional external code
  2190.     StrFile{end+1} = globals.AddCode{ii};
  2191. end
  2192.  
  2193. StrFile{end+1}='';
  2194. StrFile{end+1}='\end{pspicture}%';
  2195.  
  2196. % Add beginning strings
  2197. if globals.StandAloneFile,
  2198.    
  2199.     tempstr={'% Autor: Peter Scholz','% Email: contact@peter-scholz.net',['% Date:  ',datestr(now)],...
  2200.         '','% This file was created by fig2texPS.','% ',...
  2201.         '\documentclass{article}', ...
  2202.         '\usepackage{ifpdf}', ...
  2203.         '\ifpdf% Include pdf wrapper if running pdflatex ',...
  2204.         '  \usepackage[pdf]{pstricks}%', ...
  2205.         '  \usepackage{auto-pst-pdf}%', ...
  2206.         '\else%', ...
  2207.         '  \usepackage{pstricks}%', ...
  2208.         '\fi%', ...
  2209.         '\usepackage{pst-node, pst-plot, pst-circ}', ...
  2210.         '\usepackage{moredefs}', ...
  2211.         '\usepackage[%', ...
  2212.         ['    paperwidth = ',num2str(TotalWidth_cm*1.005,8),'cm, % add 0.5%'], ...
  2213.         ['    paperheight= ',num2str(TotalHeight_cm*1.005,8),'cm, % add 0.5%'], ...
  2214.         '    lmargin    = -5.25mm, % do not know why this offset is needed.', ...
  2215.         '    rmargin    = 0mm, %', ...
  2216.         '    tmargin    = 0mm, %', ...
  2217.         '    bmargin    = 0mm, %', ...
  2218.         '    ]{geometry}', ...
  2219.         '\begin{document}',''};
  2220.     StrFile={tempstr{:},StrFile{1:end}};
  2221.     StrFile={StrFile{1:end}, '', '\end{document}'};
  2222.    
  2223. else
  2224.    
  2225.     tempstr={'% Autor: Peter Scholz','% Email: contact@peter-scholz.net',['% Date:  ',datestr(now)],...
  2226.         '%','% This file was created by fig2texPS. Note, that the packages',...
  2227.         '% pstricks, pst-node, pst-plot, pst-circ and moredefs are required.', ...
  2228.         '% Also, ifpdf package is require to allow running pdflatex.', ...
  2229.         '% If so, remember to run pdflatex --shell-escape file.tex.', ...
  2230.         '% A minimal example code could be:','%',...
  2231.         '% \documentclass{article}', ...
  2232.         '% \usepackage{ifpdf}', ...
  2233.         '% \ifpdf% Include pdf wrapper if running pdflatex ',...
  2234.         '%   \usepackage[pdf]{pstricks}%', ...
  2235.         '%   \usepackage{auto-pst-pdf}%', ...
  2236.         '% \else%', ...
  2237.         '%  \usepackage{pstricks}%', ...
  2238.         '% \fi%', ...
  2239.         '% \begin{document}', ...
  2240.         '% \input{fig1.tex}', ...
  2241.         '% \end{document}','%'};
  2242.     StrFile={tempstr{:},StrFile{1:end}};
  2243. end
  2244.  
  2245. warning(s); % turn on specified warnings again
  2246. % PRINT TO FILE
  2247.  
  2248. % Check if file already exists
  2249. if exist(fullfile(globals.pathname,globals.filename)),
  2250.     % Construct a questdlg with three options
  2251.     choice = questdlg('File already exists. Replace it?', ...
  2252.         'Overwrite file', ...
  2253.         'Yes','No','Cancel','No');
  2254.     switch choice
  2255.         case 'Yes'
  2256.             fid = fopen(fullfile(globals.pathname,globals.filename),'wt');
  2257.             for ii=1:length(StrFile)-1,
  2258.                 wrstr=StrFile{ii};
  2259.                 fprintf(fid,'%s\n',wrstr);
  2260.             end
  2261.             fprintf(fid,'%s',StrFile{end}); % last line without 'return'
  2262.             fclose(fid);
  2263.             disp('File successfully written.')
  2264.     end
  2265.    
  2266. else
  2267.    
  2268.     fid = fopen(fullfile(globals.pathname,globals.filename),'wt');
  2269.     for ii=1:length(StrFile)-1,
  2270.         wrstr=StrFile{ii};
  2271.         fprintf(fid,'%s\n',wrstr);
  2272.     end
  2273.     fprintf(fid,'%s',StrFile{end}); % last line withour 'return'
  2274.     fclose(fid);
  2275.     disp('File successfully written.')
  2276.    
  2277. end
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283. % close figure
  2284. close(fig.figh)
  2285.  
  2286.  
  2287. % -------------------------------------------------------------------------
  2288. % END OF MAIN FUNCTION ----------------------------------------------------
  2289. % -------------------------------------------------------------------------
  2290.  
  2291.  
  2292.  
  2293.  
  2294. %%
  2295.  
  2296. % SUBFUNCTIONS
  2297.  
  2298.     function linestyle = convert_lineStyle(lsty)
  2299.         % Convert the line style to tex names,
  2300.         % lsty is a cell array
  2301.         if not(iscell(lsty)), lsty={lsty}; end
  2302.         for ii_lst=1:length(lsty)
  2303.             if isempty(lsty{ii_lst}),linestyle{ii_lst}='none';
  2304.             else
  2305.                 switch lsty{ii_lst}
  2306.                     case 'none'
  2307.                         linestyle{ii_lst}='none';
  2308.                     case '-'
  2309.                         linestyle{ii_lst}='solid';
  2310.                     case ':'
  2311.                         linestyle{ii_lst}='dashed,dash=2pt 3pt';
  2312.                     case '--'
  2313.                         linestyle{ii_lst}='dashed';
  2314.                     case '-.'
  2315.                         linestyle{ii_lst}='dashed,dash=3pt 2pt 1pt 2pt';
  2316.                     otherwise
  2317.                         linestyle{ii_lst}='solid';
  2318.                 end
  2319.             end
  2320.         end
  2321.     end
  2322.  
  2323.  
  2324.     function marker = convert_Marker(mrk)
  2325.         % Convert the line style to tex names,
  2326.         % lsty is a cell array
  2327.         if not(iscell(mrk)), mrk={mrk}; end
  2328.         for ii=1:length(mrk)
  2329.             switch mrk{ii}
  2330.                 case '+',           marker{ii}='B+';
  2331.                 case 'o',           marker{ii}='Bo';
  2332.                 case '*',           marker{ii}='Basterisk';
  2333.                 case '.',           marker{ii}='*';
  2334.                 case 'x',           marker{ii}='B|';        %%%%%% different
  2335.                 case 'square',      marker{ii}='Bsquare';
  2336.                 case 'diamond',     marker{ii}='diamond';
  2337.                 case '^',           marker{ii}='Btriangle';
  2338.                 case 'v',           marker{ii}='square*';   %%%%%% different
  2339.                 case '>',           marker{ii}='diamond*';  %%%%%% different
  2340.                 case '<',           marker{ii}='triangle*'; %%%%%% different
  2341.                 case 'pentagram',   marker{ii}='Bpentagon';
  2342.                 case 'hexagram',    marker{ii}='pentagon*'; %%%%%% different
  2343.                 otherwise
  2344.                     marker{ii}='none';
  2345.             end
  2346.         end
  2347.     end
  2348.  
  2349.  
  2350.     function [fig,globals] = update_figure_geometry(fig,globals)
  2351.         % This function generstes a gui, where some parameters can be set, the
  2352.         % figure is redrawn afterwards.
  2353.        
  2354.         exit_flag=0; % init
  2355.         % AXES:
  2356.         set(fig.axh,'Units','pixels'); ap=get(fig.axh,'Position');
  2357.         if ~isempty(ahSecond)
  2358.             set(fig.axh2,'Units','pixels'); ap2=get(fig.axh2,'Position');
  2359.         end
  2360.        
  2361.         % FIGURE:
  2362.         set(fig.figh,'Units','pixels');
  2363.         fp=get(fig.figh,'Position');
  2364.         topSpace=fp(4)-ap(4)-ap(2);
  2365.         globals.FigAxWidthFac=fp(3)/ap(3);
  2366.        
  2367.         % Create GUI figure
  2368.         guisize=[260 fp(4)]; % pixel (300 x 200)
  2369.         guisize=[310 420];
  2370.         guiPos=[fp(1)+fp(3),fp(2),guisize];
  2371.        
  2372.         if isempty(globals.heightFactor), % set height factor automatically if not specified
  2373.             globals.heightFactor=ap(4)/ap(3);
  2374.         else
  2375.             update; % update figure
  2376.         end
  2377.        
  2378.         fGui = figure('units','pixels','Position',guiPos,...
  2379.             'menubar','none','name','Figure Export Properties',...
  2380.             'numbertitle','off','resize','off','WindowStyle','modal',...
  2381.             'Color',get(0,'defaultuicontrolbackgroundcolor'),...
  2382.             'CloseRequestFcn',@UImenuExit_Callback);
  2383.         % panels
  2384.         uipanelGeometry = uipanel('parent',fGui,'units','pixels',...
  2385.             'position',[10 150 290 260],'title','Geometry Settings',...
  2386.             'FontSize',9,'FontWeight','bold');
  2387.         uipanelAuto = uipanel('parent',uipanelGeometry,'units','pixels',...
  2388.             'position',[10 10 130 130],'title','Auto (set by textsize)',...
  2389.             'FontSize',8,'FontWeight','normal');
  2390.         uipanelManual = uipanel('parent',uipanelGeometry,'units','pixels',...
  2391.             'position',[150 10 130 130],'title','Manual',...
  2392.             'FontSize',8,'FontWeight','normal');
  2393.         uipanelMisc = uipanel('parent',fGui,'units','pixels',...
  2394.             'position',[10 10 290 130],'title','Misc',...
  2395.             'FontSize',9,'FontWeight','bold');
  2396.        
  2397.         % fields
  2398.         WidthTextPre = uicontrol(uipanelGeometry,'style','text','units','pixels',...
  2399.             'position',[10 210 75 17],'string','Width / cm:',...
  2400.             'HorizontalAlignment','left');
  2401.         editWidth = uicontrol(uipanelGeometry,'style','edit','units','pixels',...
  2402.             'position',[90 210 50 20],'string',globals.plotwidth,'BackgroundColor','white',...
  2403.             'Enable','on',...
  2404.             'Callback',@editWidth_callback);
  2405.         if strcmp(globals.widthType,'axes'), % test if axes is activated
  2406.             axtrue=1; figtrue=0; else axtrue=0; figtrue=1;
  2407.         end
  2408.         radiobuttonFig = uicontrol(uipanelGeometry,'style','radiobutton',...
  2409.             'units','pixels','position',[150 210 50 20],...
  2410.             'string','Figure','Value',figtrue,'Enable','on',...
  2411.             'Callback',@radiobuttonFig_callback);
  2412.         radiobuttonAxes = uicontrol(uipanelGeometry,'style','radiobutton',...
  2413.             'units','pixels','position',[225 210 50 20],...
  2414.             'string','Axes','Value',axtrue,'Enable','on',...
  2415.             'Callback',@radiobuttonAxes_callback);
  2416.         textFactor = uicontrol(uipanelGeometry,'style','text',...
  2417.             'units','pixels','position',[10 180 75 17],...
  2418.             'string','Height /  Width:','HorizontalAlignment','left');
  2419.         editFactor = uicontrol(uipanelGeometry,'style','edit','units','pixels',...
  2420.             'position',[90 180 50 20],'string',globals.heightFactor,'BackgroundColor','white',...
  2421.             'Enable','on',...
  2422.             'Callback',@editFactor_callback);
  2423.         radiobuttonAspectRatio = uicontrol(uipanelGeometry,'style','radiobutton',...
  2424.             'units','pixels','position',[150 180 80 20],...
  2425.             'string','Axis equal','Value',0,...
  2426.             'Callback',@radiobuttonAspectRatio_callback);
  2427.         radiobuttonSquare = uicontrol(uipanelGeometry,'style','radiobutton',...
  2428.             'units','pixels','position',[225 180 55 20],...
  2429.             'string','Square','Value',0,...
  2430.             'Callback',@radiobuttonSquare_callback);
  2431.         textSpaceSurrounding = uicontrol(uipanelGeometry,'style','text',...
  2432.             'units','pixels','position',[10 145 180 17],'FontWeight','bold',...
  2433.             'string','Space surrounding the axes:','HorizontalAlignment','left');
  2434.        
  2435.         sliderFont = uicontrol(uipanelAuto,'style','slider',...
  2436.             'units','pixels','position',[10 85 105 20],...
  2437.             'string','Figure','BackgroundColor','white',...
  2438.             'Min',globals.labelsepMin,'Max',globals.labelsepMax,...
  2439.             'Value',globals.labelsep,'SliderStep',[1/(globals.labelsepMax-globals.labelsepMin),0],...
  2440.             'Callback',@sliderFont_callback);
  2441.         radiobuttonCenterAxes = uicontrol(uipanelAuto,'style','radiobutton',...
  2442.             'units','pixels','position',[10 60 80 20],...
  2443.             'string','Center axes','Value',globals.centerAxes,'Enable','on',...
  2444.             'Callback',@radiobuttonCenterAxes_callback);
  2445.         texthorizontally = uicontrol(uipanelAuto,'style','text',...
  2446.             'units','pixels','position',[28 45 75 17],...
  2447.             'string','horizontally','HorizontalAlignment','left');
  2448.        
  2449.         LeftPre = uicontrol(uipanelManual,'style','text','units','pixels',...
  2450.             'position',[10 85 37 17],'string','Left:','HorizontalAlignment','left');
  2451.         BottomPre = uicontrol(uipanelManual,'style','text','units','pixels',...
  2452.             'position',[10 60 37 17],'string','Bottom:','HorizontalAlignment','left');
  2453.         RightPre = uicontrol(uipanelManual,'style','text','units','pixels',...
  2454.             'position',[10 35 37 17],'string','Right:','HorizontalAlignment','left');
  2455.         TopPre = uicontrol(uipanelManual,'style','text','units','pixels',...
  2456.             'position',[10 10 37 17],'string','Top:','HorizontalAlignment','left');
  2457.         LeftPost = uicontrol(uipanelManual,'style','text','units','pixels',...
  2458.             'position',[105 85 20 17],'string','cm','HorizontalAlignment','left');
  2459.         BottomPost = uicontrol(uipanelManual,'style','text','units','pixels',...
  2460.             'position',[105 60 20 17],'string','cm','HorizontalAlignment','left');
  2461.         RightPost = uicontrol(uipanelManual,'style','text','units','pixels',...
  2462.             'position',[105 35 20 17],'string','cm','HorizontalAlignment','left');
  2463.         TopPost = uicontrol(uipanelManual,'style','text','units','pixels',...
  2464.             'position',[105 10 20 17],'string','cm','HorizontalAlignment','left');
  2465.         globals.ManualTightStrings = {'---','---','---','---'}; % init
  2466.         globals.tightInset_cmBackup= globals.tightInset_cm; % copy
  2467.         if ~ isempty (globals.tightInset_cm)
  2468.             for ii=1:4,
  2469.                 globals.ManualTightStrings{ii} = num2str(globals.tightInset_cm (ii));
  2470.             end
  2471.         else
  2472.             globals.tightInset_cmBackup = [1 1 1 1];
  2473.         end
  2474.         if axtrue, EnableTight = 'on'; else EnableTight = 'off'; end
  2475.         editLeft = uicontrol(uipanelManual,'style','edit','units','pixels',...
  2476.             'position',[50 85 50 20],'string',globals.ManualTightStrings{1},'BackgroundColor','white',...
  2477.             'Enable','on','Enable',EnableTight,'Callback',@editLeft_callback);
  2478.         editBottom = uicontrol(uipanelManual,'style','edit','units','pixels',...
  2479.             'position',[50 60 50 20],'string',globals.ManualTightStrings{2},'BackgroundColor','white',...
  2480.             'Enable','on','Enable',EnableTight,'Callback',@editBottom_callback);
  2481.         editRight = uicontrol(uipanelManual,'style','edit','units','pixels',...
  2482.             'position',[50 35 50 20],'string',globals.ManualTightStrings{3},'BackgroundColor','white',...
  2483.             'Enable','on','Enable',EnableTight,'Callback',@editRight_callback);
  2484.         editTop = uicontrol(uipanelManual,'style','edit','units','pixels',...
  2485.             'position',[50 10 50 20],'string',globals.ManualTightStrings{4},'BackgroundColor','white',...
  2486.             'Enable','on','Enable',EnableTight,'Callback',@editTop_callback);
  2487.        
  2488.         radiobuttonBoundingBox = uicontrol(uipanelMisc,'style','radiobutton',...
  2489.             'units','pixels','position',[10 90 120 20],...
  2490.             'string','Draw figure outline','Value',globals.BoundingBox,...
  2491.             'Callback',@radiobuttonBoundingBox_callback);
  2492.         radiobuttonStandAloneFile = uicontrol(uipanelMisc,'style','radiobutton',...
  2493.             'units','pixels','position',[170 90 100 20],...
  2494.             'string','Stand-alone file','Value',globals.StandAloneFile,...
  2495.             'Callback',@radiobuttonStandAloneFile_callback);
  2496.         radiobuttonReducePoints = uicontrol(uipanelMisc,'style','radiobutton',...
  2497.             'units','pixels','position',[10 68 170 20],...
  2498.             'string','Reduce data points, Factor:','Value',1,...
  2499.             'Callback',@radiobuttonReducePoints_callback);
  2500.         editReducePointsFactor = uicontrol(uipanelMisc,'style','edit','units','pixels',...
  2501.             'position',[170 68 50 20],'string',globals.PointReduceFactor,'BackgroundColor','white',...
  2502.             'Enable','on',...
  2503.             'Callback',@editReducePointsFactor_callback);
  2504.         LegendText = uicontrol(uipanelMisc,'style','text','units','pixels',...
  2505.             'position',[10 40 75 17],'string','Legend style:',...
  2506.             'HorizontalAlignment','left');
  2507.        
  2508.        
  2509.         globals.LegendStyle = {'Rectangular Box', ...
  2510.             'Rounded corners', 'Shadowbox', 'No Box'};
  2511.         globals.LegendBoxTeXcode = get_LegendTexCode_Pre (globals.idx_LegendStyle);
  2512.        
  2513.         popupLegendStyle = uicontrol(uipanelMisc,'Style','popupmenu',...
  2514.             'units','pixels','position',[80 40 120 20],...
  2515.             'String', globals.LegendStyle,'BackgroundColor','white',...
  2516.             'Value', globals.idx_LegendStyle, ...
  2517.             'Callback',@popupLegendStyle_callback);
  2518.         SaveText = uicontrol(uipanelMisc,'style','text','units','pixels',...
  2519.             'position',[10 10 75 17],'string','Export to file:',...
  2520.             'HorizontalAlignment','left');
  2521.         popupSaveFile = uicontrol(uipanelMisc,'Style','popupmenu',...
  2522.             'units','pixels','position',[80 10 120 20],...
  2523.             'String', {globals.filename,'Select...'},'BackgroundColor','white',...
  2524.             'Callback',@popupSaveFile_callback);
  2525.         pushbuttonDone = uicontrol(uipanelMisc,'style','pushbutton','units','pixels',...
  2526.             'position',[210 10 70 30],'string','Start',...
  2527.             'Callback',@DoneButton_callback);
  2528.        
  2529.         if globals.ShowGUI
  2530.             uiwait; % wait until figure is deleted
  2531.         else
  2532.             DoneButton_callback;
  2533.         end
  2534.        
  2535.         function editWidth_callback(hObject,eventdata)
  2536.             globals.plotwidth=str2num(get(editWidth,'string'));
  2537.         end
  2538.        
  2539.         function radiobuttonAxes_callback(hObject,eventdata)
  2540.             isOn=get(radiobuttonAxes,'Value');
  2541.             if isOn,
  2542.                 set(radiobuttonFig,'Value',0)
  2543.                 globals.widthType='axes';
  2544.                 set(editLeft,'Enable','on');  set(editBottom,'Enable','on');
  2545.                 set(editRight,'Enable','on'); set(editTop,'Enable','on');
  2546.             else
  2547.                 set(radiobuttonFig,'Value',1)
  2548.                 globals.widthType='figure';
  2549.                 set(editLeft,'Enable','off');  set(editBottom,'Enable','off');
  2550.                 set(editRight,'Enable','off'); set(editTop,'Enable','off');
  2551.             end
  2552.         end
  2553.        
  2554.         function radiobuttonFig_callback(hObject,eventdata)
  2555.             isOn=get(radiobuttonFig,'Value');
  2556.             if isOn,
  2557.                 set(radiobuttonAxes,'Value',0)
  2558.                 globals.widthType='figure';
  2559.                 set(editLeft,'Enable','off');  set(editBottom,'Enable','off');
  2560.                 set(editRight,'Enable','off'); set(editTop,'Enable','off');
  2561.             else
  2562.                 set(radiobuttonAxes,'Value',1)
  2563.                 globals.widthType='axes';
  2564.                 set(editLeft,'Enable','on');  set(editBottom,'Enable','on');
  2565.                 set(editRight,'Enable','on'); set(editTop,'Enable','on');
  2566.             end
  2567.         end
  2568.        
  2569.         function radiobuttonCenterAxes_callback(hObject,eventdata)
  2570.             isOn=get(radiobuttonCenterAxes,'Value');
  2571.             if isOn,
  2572.                 globals.centerAxes=1;
  2573.             else
  2574.                 globals.centerAxes=0;
  2575.             end
  2576.             globals.tightInset_cm = []; % backup still exist
  2577.             set(editLeft,'String',globals.ManualTightStrings{1});
  2578.             set(editBottom,'String',globals.ManualTightStrings{2});
  2579.             set(editRight,'String',globals.ManualTightStrings{3});
  2580.             set(editTop,'String',globals.ManualTightStrings{4});
  2581.         end
  2582.        
  2583.         function radiobuttonReducePoints_callback(hObject,eventdata)
  2584.             reduceOn=get(radiobuttonReducePoints,'Value');
  2585.             if reduceOn,
  2586.                 set(radiobuttonReducePoints,'Value',1)
  2587.                 set(editReducePointsFactor,'Enable','on')
  2588.                 globals.PointReduceFactor=str2num(get(editReducePointsFactor,'string'));
  2589.             else
  2590.                 set(radiobuttonReducePoints,'Value',0)
  2591.                 set(editReducePointsFactor,'Enable','off')
  2592.                 globals.PointReduceFactor=0; % reduce off
  2593.             end
  2594.         end
  2595.        
  2596.         function editReducePointsFactor_callback(hObject,eventdata)
  2597.             globals.PointReduceFactor=str2num(get(editReducePointsFactor,'string'));
  2598.         end
  2599.        
  2600.         function editFactor_callback(hObject,eventdata)
  2601.             globals.heightFactor=str2num(get(editFactor,'string'));
  2602.             set(radiobuttonAspectRatio,'Value',0)
  2603.             set(radiobuttonSquare,'Value',0)
  2604.             update;
  2605.         end
  2606.        
  2607.         function radiobuttonAspectRatio_callback(hObject,eventdata)
  2608.             globals.heightFactor=(fig.YLim(2)-fig.YLim(1))/(fig.XLim(2)-fig.XLim(1));
  2609.             set(editFactor,'string',globals.heightFactor);
  2610.             set(radiobuttonSquare,'Value',0)
  2611.             update;
  2612.         end
  2613.        
  2614.         function radiobuttonSquare_callback(hObject,eventdata)
  2615.             globals.heightFactor=1;
  2616.             set(editFactor,'string',globals.heightFactor);
  2617.             set(radiobuttonAspectRatio,'Value',0)
  2618.             update;
  2619.         end
  2620.        
  2621.         function editLeft_callback(hObject,eventdata)
  2622.             globals.tightInset_cm(1) = str2num(get(editLeft,'string'));
  2623.             globals.tightInset_cmBackup(1) = globals.tightInset_cm(1);
  2624.             globals.tightInset_cm(2:4) = globals.tightInset_cmBackup(2:4);
  2625.             globals.centerAxes = 0; set(radiobuttonCenterAxes,'Value',0); % deactivate
  2626.             set(editLeft,'string',globals.tightInset_cm(1)); % update
  2627.             set(editBottom,'string',globals.tightInset_cm(2)); % update
  2628.             set(editRight,'string',globals.tightInset_cm(3)); % update
  2629.             set(editTop,'string',globals.tightInset_cm(4)); % update
  2630.             update;
  2631.         end
  2632.        
  2633.         function editBottom_callback(hObject,eventdata)
  2634.             globals.tightInset_cm(2) = str2num(get(editBottom,'string'));
  2635.             globals.tightInset_cmBackup(2) = globals.tightInset_cm(2);
  2636.             globals.tightInset_cm(1) = globals.tightInset_cmBackup(1);
  2637.             globals.tightInset_cm(3:4) = globals.tightInset_cmBackup(3:4);
  2638.             globals.centerAxes = 0; set(radiobuttonCenterAxes,'Value',0); % deactivate
  2639.             set(editLeft,'string',globals.tightInset_cm(1)); % update
  2640.             set(editBottom,'string',globals.tightInset_cm(2)); % update
  2641.             set(editRight,'string',globals.tightInset_cm(3)); % update
  2642.             set(editTop,'string',globals.tightInset_cm(4)); % update
  2643.             update;
  2644.         end
  2645.        
  2646.         function editRight_callback(hObject,eventdata)
  2647.             globals.tightInset_cm(3) = str2num(get(editRight,'string'));
  2648.             globals.tightInset_cmBackup(3) = globals.tightInset_cm(3);
  2649.             globals.tightInset_cm(1:2) = globals.tightInset_cmBackup(1:2);
  2650.             globals.tightInset_cm(4) = globals.tightInset_cmBackup(4);
  2651.             globals.centerAxes = 0; set(radiobuttonCenterAxes,'Value',0); % deactivate
  2652.             set(editLeft,'string',globals.tightInset_cm(1)); % update
  2653.             set(editBottom,'string',globals.tightInset_cm(2)); % update
  2654.             set(editRight,'string',globals.tightInset_cm(3)); % update
  2655.             set(editTop,'string',globals.tightInset_cm(4)); % update
  2656.             update;
  2657.         end
  2658.        
  2659.         function editTop_callback(hObject,eventdata)
  2660.             globals.tightInset_cm(4) = str2num(get(editTop,'string'));
  2661.             globals.tightInset_cmBackup(4) = globals.tightInset_cm(4);
  2662.             globals.tightInset_cm(1:3) = globals.tightInset_cmBackup(1:3);
  2663.             globals.centerAxes = 0; set(radiobuttonCenterAxes,'Value',0); % deactivate
  2664.             set(editLeft,'string',globals.tightInset_cm(1)); % update
  2665.             set(editBottom,'string',globals.tightInset_cm(2)); % update
  2666.             set(editRight,'string',globals.tightInset_cm(3)); % update
  2667.             set(editTop,'string',globals.tightInset_cm(4)); % update
  2668.             update;
  2669.         end
  2670.        
  2671.         function sliderFont_callback(hObject,eventdata)
  2672.             globals.labelsep=get(sliderFont,'Value'); % value
  2673.             set(fig.axh,'FontSize',globals.labelsep);
  2674.             set(get(fig.axh,'Title'),'FontSize',globals.labelsep);
  2675.             set(get(fig.axh,'Xlabel'),'FontSize',globals.labelsep);
  2676.             set(get(fig.axh,'Ylabel'),'FontSize',globals.labelsep);
  2677.             if ~isempty(ahSecond)
  2678.                 set(fig.axh2,'FontSize',globals.labelsep);
  2679.                 set(get(fig.axh2,'Ylabel'),'FontSize',globals.labelsep);
  2680.             end
  2681.             globals.tightInset_cm = []; % backup still exist
  2682.             set(editLeft,'String',globals.ManualTightStrings{1});
  2683.             set(editBottom,'String',globals.ManualTightStrings{2});
  2684.             set(editRight,'String',globals.ManualTightStrings{3});
  2685.             set(editTop,'String',globals.ManualTightStrings{4});
  2686.             update;
  2687.         end
  2688.        
  2689.         function radiobuttonBoundingBox_callback(hObject,eventdata)
  2690.             if get(radiobuttonBoundingBox,'Value') == 1, %
  2691.                 globals.BoundingBox=1;
  2692.             else
  2693.                 globals.BoundingBox=0;
  2694.             end
  2695.         end
  2696.        
  2697.         function radiobuttonStandAloneFile_callback(hObject,eventdata)
  2698.             if get(radiobuttonStandAloneFile,'Value') == 1, %
  2699.                 globals.StandAloneFile=1;
  2700.             else
  2701.                 globals.StandAloneFile=0;
  2702.             end
  2703.         end
  2704.        
  2705.        
  2706.        
  2707.         function out = get_LegendTexCode_Pre (val)
  2708.             switch val
  2709.                 case 1, % rectangular box
  2710.                     out = {'\psframebox[framesep=0pt,linewidth=\AxesLineWidth]{\psframebox*{\begin{tabular}{l}'}; % init text for framebox
  2711.                 case 2, % rounded corners
  2712.                     out = {'\psframebox[fillstyle=solid,cornersize=absolute,linearc=5pt,framesep=0pt,linewidth=\AxesLineWidth]{\psframebox[linestyle=none]{\begin{tabular}{l}'}; % init text for rounded corners
  2713.                 case 3, % shadowbox
  2714.                     out = {'\psshadowbox[framesep=0pt,linewidth=\AxesLineWidth]{\psframebox*{\begin{tabular}{l}'}; % init text for shadowbox
  2715.                 case 4, % no box
  2716.                     out = {'{\psframebox*[framesep=0pt]{\begin{tabular}{l}'}; % init text for framebox
  2717.             end
  2718.         end
  2719.        
  2720.         function popupLegendStyle_callback(hObject,eventdata)
  2721.             globals.idx_LegendStyle = get(popupLegendStyle,'Value');
  2722.             globals.LegendBoxTeXcode = get_LegendTexCode_Pre (globals.idx_LegendStyle);
  2723.         end
  2724.        
  2725.         function popupSaveFile_callback(hObject,eventdata)
  2726.             if get(popupSaveFile,'Value')==2, % choose new filename
  2727.                 [filename,pathname] = uiputfile(fullfile(globals.pathname,globals.filename));
  2728.                 if ischar(filename) , % correct file
  2729.                     globals.filename=filename;
  2730.                     globals.pathname=pathname;
  2731.                 end
  2732.                 set(popupSaveFile,'String',{globals.filename,'Select...'})
  2733.                 set(popupSaveFile,'Value',1)
  2734.             end
  2735.         end
  2736.        
  2737.         function DoneButton_callback(hObject,eventdata)
  2738.             if get(radiobuttonAxes,'Value')==1, % width for axes
  2739.                 globals.FigAxWidthFac=1;
  2740.             end
  2741.             delete(fGui);  % delete figure and exit
  2742.         end
  2743.        
  2744.         function UImenuExit_Callback(hObject,evendata)
  2745.             close(fig.figh)
  2746.             delete(fGui)
  2747.             exit_flag=1;
  2748.         end
  2749.        
  2750.         function update % update figure
  2751.             % update figure and axes
  2752.             if not(isempty(fig.LegendLoc)),
  2753.                 % if a legend is present, it must first be disabled when
  2754.                 % changing the figure size, it is replotted after change in
  2755.                 % figure size
  2756.                 legend(fig.axh,'off')
  2757.             end
  2758.             ap(4)=globals.heightFactor*ap(3); % update height of axes
  2759.             fp(4)=topSpace+ap(4)+ap(2); % update height of figure
  2760.             set(fig.figh,'Units','pixels','Position',round(fp));
  2761.             set(fig.axh,'Units','pixels','Position',round(ap));
  2762.             set(fig.axh,'XTickLabel',fig.XTickLabel);
  2763.             xlabel(fig.axh,[fig.XLabel,fig.XLabelPost],'FontSize',globals.labelsep,'interpreter','none');
  2764.             ylabel(fig.axh,[fig.YLabel,fig.YLabelPost],'FontSize',globals.labelsep,'interpreter','none');
  2765.             title(fig.axh,fig.Title,'FontSize',globals.labelsep,'interpreter','none');
  2766.             if not(isempty(fig.LegendLoc)), % a legend is replotted
  2767.                 legend(fig.axh,fig.LegendStr,'Location',fig.LegendLoc,'interpreter','none')
  2768.             end
  2769.             if ~isempty(ahSecond)
  2770.                 ap2(4)=globals.heightFactor*ap2(3); % update height of axes
  2771.                 set(fig.axh2,'Position',ap2);
  2772.                 ylabel(fig.axh2,[fig.YLabel2,fig.YLabelPost2],'FontSize',globals.labelsep,'interpreter','none');
  2773.             end
  2774.             % movegui(fig.figh,'center'); % shift figure to screen center
  2775.         end
  2776.        
  2777.         if not(exit_flag)
  2778.             update
  2779.             set(fig.axh,'Units','normalized');
  2780.         end
  2781.     end
  2782.  
  2783.  
  2784. % Copied from Ercan Solak's file fig2tex.m
  2785.     function resstr = strfill(genstr,fpar)
  2786.         %STRFILL Replace the numbered tokens with parameters
  2787.         %   STRFILL(GENSTR,FPAR) replaces the numbered token
  2788.         %   #i# in the string GENSTR with the ith element
  2789.         %   of the cellarray FPAR. This script is used by
  2790.         %   FIG2TEX.
  2791.        
  2792.         resstr=genstr;
  2793.         for ii_str=1:length(fpar)
  2794.             if isnumeric(fpar{ii_str})
  2795.                 reptoken = num2str(fpar{ii_str},globals.FloatingPointFormat);
  2796.             else
  2797.                 reptoken = fpar{ii_str};
  2798.             end;
  2799.             resstr = strrep(resstr,['#',num2str(ii_str),'#'],reptoken);
  2800.         end;
  2801.        
  2802.     end
  2803.  
  2804.  
  2805. % FUNCTION REDUCE_LINE
  2806. %
  2807. %  COPY OF MATFIG2PGF
  2808.  
  2809. %--------------------------------------------------------------------------
  2810.     function [ reduced_xydata ] = reduce_line( xydata, maxerror )
  2811.        
  2812.        
  2813.         N = size(xydata,2);
  2814.        
  2815.         if (maxerror <= 0) || (N < 3)
  2816.             reduced_xydata = xydata;
  2817.             return
  2818.         end
  2819.        
  2820.         xydata = minmaxdecimation(xydata, 4*maxerror);
  2821.        
  2822.         N = size(xydata,2);
  2823.        
  2824.         plotPoints = 1;
  2825.         lastPlotted = 1;
  2826.        
  2827.         xdata = xydata(1,:);
  2828.         ydata = xydata(2,:);
  2829.        
  2830.         for i = 3:N
  2831.             % Calculate distance
  2832.             % see http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
  2833.             % x1 = xydata(:,i)  x2 = xydata(:,lastPlotted)  x0 = all points
  2834.             % between x1 and x2
  2835.             % See also: http://astronomy.swin.edu.au/~pbourke/geometry/pointline/
  2836.             p1 = xydata(:,i);
  2837.             p2 = xydata(:,lastPlotted);
  2838.             dp = sqrt(sum((p1-p2).^2));
  2839.             frac1 = ( xdata(lastPlotted+1:i-1)-xdata(i) ) .* ( xdata(lastPlotted)-xdata(i) );
  2840.             frac1 = frac1 + ( ydata(lastPlotted+1:i-1)-ydata(i) ) .* ( ydata(lastPlotted)-ydata(i) );
  2841.             u = frac1 ./ sum((p2-p1).^2);
  2842.            
  2843.             % Convert u to the distance from the point to p1 or p2
  2844.             % For points where the closest point on line p1-p2 is outside of p1 and
  2845.             % p2 u is now the distance to p1 or p2. When the closest point was
  2846.             % between p1 and p2 u will be zero.
  2847.             u((u > 0) & (u <= 1)) = 0;
  2848.             u(u>1) = dp*(u(u>1)-1);
  2849.             u(u<0) = dp*(-u(u<0));
  2850.            
  2851.             % Calculate shortest distance from point to line (p1-p2)
  2852.             a = xdata(lastPlotted)-xdata(i);
  2853.             b = ydata(lastPlotted)-ydata(i);
  2854.             c = xdata(i)-xdata(lastPlotted+1:i-1);
  2855.             d = ydata(i)-ydata(lastPlotted+1:i-1);
  2856.             frac1 = abs(a.*d-b.*c);
  2857.             frac2 = sqrt(sum((xydata(:,lastPlotted)-xydata(:,i)).^2));
  2858.             d = frac1./frac2;
  2859.            
  2860.             d = sqrt(d.^2 + u.^2);
  2861.            
  2862.             if max(d) > maxerror
  2863.                 lastPlotted = i-1;
  2864.                 plotPoints = [plotPoints lastPlotted];
  2865.             end
  2866.            
  2867.         end
  2868.        
  2869.         plotPoints = [plotPoints N];
  2870.         if N > 5
  2871.             reduced_xydata = xydata(:,plotPoints);
  2872.         else
  2873.             reduced_xydata = xydata;
  2874.         end
  2875.         if N ~= size(reduced_xydata,2)
  2876.             fprintf('reduced data points: org: %d -> red: %d\n',...
  2877.                 N, size(reduced_xydata,2));
  2878.         end
  2879.        
  2880.         %-- end of function reduce_line -------------------------------------------
  2881.        
  2882.     end
  2883.  
  2884. % FUNCTION MINMAXDECIMATION
  2885. %
  2886. %  COPY OF MATFIG2PGF
  2887. %
  2888.     function [ decimatedXydata ] = minmaxdecimation( xydata, columnWidth )
  2889.        
  2890.         xdata = xydata(1,:);
  2891.         ydata = xydata(2,:);
  2892.         minx = min(xdata);
  2893.         maxx = max(xdata);
  2894.         N = (maxx-minx)/columnWidth;  % number of columns
  2895.        
  2896.         % dx = xdata(i+1)-xdata(i) is the same for all values. Otherwise this
  2897.         % function is not going to work.
  2898.         dx = diff(xdata);
  2899.         maxdx = max(dx);
  2900.         mindx = min(dx);
  2901.         dx = median(dx);
  2902.        
  2903.         % If dx is not the same for all values OR
  2904.         % if the number of columns is less than 0.5*data length
  2905.         % then we can not use min-max decimation
  2906.         if ( (maxdx-mindx)/dx > 1e-6 ) || ( N > 0.5*length(xdata) )
  2907.             decimatedXydata = xydata;
  2908.             return;
  2909.         end
  2910.        
  2911.         decimatedXydata = [];
  2912.         lastIndex = 0;
  2913.         for i = 1:ceil(N)
  2914.             thisIndex = min( floor(i*columnWidth/dx), length(xdata) );
  2915.             [miny, minIndex] = min(ydata(lastIndex+1:thisIndex));
  2916.             [maxy, maxIndex] = max(ydata(lastIndex+1:thisIndex));
  2917.             minIndex = minIndex+lastIndex;
  2918.             maxIndex = maxIndex+lastIndex;
  2919.             if minIndex < maxIndex
  2920.                 decimatedXydata = [decimatedXydata [xdata(minIndex);miny] [xdata(maxIndex);maxy]];
  2921.             else
  2922.                 decimatedXydata = [decimatedXydata [xdata(maxIndex);maxy] [xdata(minIndex);miny]];
  2923.             end
  2924.             lastIndex = thisIndex;
  2925.         end
  2926.         if size(decimatedXydata,2) > 10
  2927.             fprintf('  min-max decimation: original %d  decimated %d\n', size(xydata,2), size(decimatedXydata,2));
  2928.         else
  2929.             decimatedXydata = xydata;
  2930.         end
  2931.         %- end of function minmaxdecimation ---------------------------------------
  2932.     end
  2933.  
  2934.  
  2935.  
  2936.  
  2937.     function [Pcut, Psnip] = cut_data (xd, yd, XLim, YLim)
  2938.         % cut data that are out of bounds and append them as extra lines:
  2939.        
  2940.         % Pcut is a cell array with each element being a nx2 matrix
  2941.         % containing a point in each row that belongs to a valid line
  2942.         % segment
  2943.         %
  2944.         % Psnip is a cell array with each element being a nx2 matrix
  2945.         % containing a point in each row that belongs to a valid snipped
  2946.         % that should be appended at the beginning or end
  2947.        
  2948.         % init
  2949.         P_tmp = [];
  2950.         Pcut  = {};
  2951.         Psnip = {}; % here come all snippet points
  2952.        
  2953.         % scan through all points
  2954.         for ii = 2 : length(xd), % start with second point
  2955.            
  2956.             P_curr = [xd(ii),   yd(ii)];
  2957.             P_last = [xd(ii-1), yd(ii-1)];
  2958.            
  2959.             if ~isfinite(P_curr(1)) || ~isfinite(P_curr(2)), % at least one value is nan
  2960.                
  2961.                 if ~isempty(P_tmp),
  2962.                     Pcut{end+1} = P_tmp; % add last segments to cell, ...
  2963.                     P_tmp = []; % and reset
  2964.                 end                
  2965.                
  2966.             else
  2967.                                
  2968.                 if ~P_is_in(P_curr), % not in
  2969.                    
  2970.                     if P_is_in(P_last) && ... % last point was in, new snippet
  2971.                             (isfinite(P_last(1)) && isfinite(P_last(2))), % valid
  2972.                        
  2973.                         Psnip{end+1} = [P_last; interpolate(P_curr, P_last)];
  2974.                     else % both P_curr and P_last are out
  2975.                         Psnip{end+1} = interpolate(P_curr, P_last);                        
  2976.                     end
  2977.                                                                                
  2978.                     if ~isempty(P_tmp),
  2979.                         Pcut{end+1} = P_tmp; % add last segments to cell, ...
  2980.                         P_tmp = []; % and reset
  2981.                     end
  2982.                    
  2983.                 elseif P_is_in(P_curr),
  2984.                    
  2985.                     P_tmp(end+1,:) = P_curr; % add this to main points
  2986.                    
  2987.                     if ~P_is_in(P_last) && ... % last point was not in, new snippet
  2988.                             (isfinite(P_last(1)) && isfinite(P_last(2))), % valid
  2989.                        
  2990.                         Psnip{end+1} = [interpolate(P_curr, P_last); P_curr];
  2991.                        
  2992.                     end
  2993.                    
  2994.                     % treat first and last segments special
  2995.                    
  2996.                     if ii == 2, % first element
  2997.                    
  2998.                         if P_is_in(P_last) && ... % last point was in append this point:
  2999.                             (isfinite(P_last(1)) && isfinite(P_last(2))), % valid
  3000.                            
  3001.                             P_tmp = [P_last; P_tmp];
  3002.                            
  3003.                         end
  3004.                        
  3005.                     end
  3006.                    
  3007.                     if ii == length(xd), % last element, write data
  3008.                        
  3009.                         Pcut{end+1} = P_tmp;
  3010.                        
  3011.                     end
  3012.                    
  3013.                    
  3014.                 end
  3015.             end
  3016.            
  3017.         end
  3018.        
  3019.        
  3020.         % Subfunctions:
  3021.        
  3022.         function [Pint, varargout] = interpolate(P1, P2)
  3023.        
  3024.             cut_pos = ''; % init, left, right, top, bottom
  3025.            
  3026.             if P_is_in(P1) && P_is_in(P2)
  3027.                 Pint = []; % both in, nothing to interpolate
  3028.             elseif ~P_is_in(P1) && ~P_is_in(P2) % both out, return both points                
  3029.                 % build straight line (y = m * x + b)
  3030.                 m = (P2(2) - P1(2)) / (P2(1) - P1(1));
  3031.                 b = P2(2) - m * P2(1);
  3032.                 % (x,YLim(1))
  3033.                 dx1 = (YLim(1) - b) / m;
  3034.                 if dx1 < XLim(1), dx1 = XLim(1);
  3035.                 elseif dx1 > XLim(2), dx1 = XLim(2); end
  3036.                
  3037.                 % (x,YLim(2))
  3038.                 dx2 = (YLim(2) - b) / m;
  3039.                 if dx2 < XLim(1), dx2 = XLim(1);
  3040.                 elseif dx2 > XLim(2), dx2 = XLim(2); end
  3041.                 Pint = [dx1,YLim(1);dx2,YLim(2)];
  3042.                 cut_pos = 'top-bottom';
  3043.             else
  3044.  
  3045.                 % build straight line (y = m * x + b)
  3046.                 m = (P2(2) - P1(2)) / (P2(1) - P1(1));
  3047.                 b = P2(2) - m * P2(1);
  3048.                
  3049.                 % test where straght line intersects with borders
  3050.                 if ((P1(1) >= XLim(1)) && (P2(1) < XLim(1))) || ...
  3051.                       ((P2(1) >= XLim(1)) && (P1(1) < XLim(1))), % left
  3052.                   % 'left'
  3053.                   Pint = [XLim(1), m*XLim(1)+b];
  3054.                   cut_pos = 'left';
  3055.                  
  3056.                 elseif ((P1(1) > XLim(2)) && (P2(1) <= XLim(2))) || ...
  3057.                       ((P2(1) > XLim(2)) && (P1(1) <= XLim(2))), % left
  3058.                   % 'right'
  3059.                   Pint = [XLim(2), m*XLim(2)+b];
  3060.                   cut_pos = 'right';
  3061.                  
  3062.                 elseif ((P1(2) >= YLim(1)) && (P2(2) < YLim(1))) || ...
  3063.                         ((P2(2) >= YLim(1)) && (P1(2) < YLim(1))), % left
  3064.                     % 'bottom'
  3065.                     % test for vertical line:
  3066.                     if ~isfinite(m), % vertical
  3067.                         Pint = [P2(1), YLim(1)];
  3068.                     else
  3069.                         Pint = [(YLim(1)-b)/m, YLim(1)];
  3070.                     end
  3071.                     cut_pos = 'bottom';
  3072.  
  3073.                 elseif ((P1(2) > YLim(2)) && (P2(2) <= YLim(2))) || ...
  3074.                       ((P2(2) > YLim(2)) && (P1(2) <= YLim(2))), % left
  3075.                   % 'top'
  3076.                   if ~isfinite(m), % vertical
  3077.                       Pint = [P2(1), YLim(2)];
  3078.                   else
  3079.                       Pint = [(YLim(2)-b)/m, YLim(2)];
  3080.                   end
  3081.                   cut_pos = 'top';
  3082.                  
  3083.                 else
  3084.                    
  3085.                     warning('Something went wrong')
  3086.                    
  3087.                 end
  3088.                
  3089.             end
  3090.            
  3091.             nout = max(nargout,1)-1;
  3092.             if nout == 1,
  3093.                 varargout(1) = {cut_pos};
  3094.             end
  3095.  
  3096.            
  3097.         end
  3098.        
  3099.         function answer = P_is_in(P)
  3100.             answer = false;
  3101.             x = P(1);
  3102.             y = P(2);
  3103.             if (x >= XLim(1)) && (x <= XLim(2)) && ...
  3104.                     (y >= YLim(1)) && (y <= YLim(2))
  3105.                 answer = true;
  3106.             end
  3107.         end
  3108.        
  3109.        
  3110.        
  3111.     end
  3112.  
  3113.  
  3114.  
  3115.  
  3116. % FUNCTION TEXT_CONTAINS_DOLLARSYMBOL
  3117. %
  3118. %    answer = text_contains_dollarsymbol(textin)
  3119. %
  3120. %       textin  - normal text to be tested for at least one '$'
  3121. %
  3122. %       answer - boolean answer
  3123. %--------------------------------------------------------------------------
  3124.     function answer = text_contains_dollarsymbol(textin)
  3125.         answer=false;
  3126.         if ~iscell(textin), textin={textin}; end % convert to cell
  3127.         for ii=1:length(textin),
  3128.             if iscell(textin{ii}) % if still cell, multiple lines
  3129.                 for jj=1:length(textin{ii}), % another loop for two line entries
  3130.                     if ~isempty(strfind(textin{ii}{jj},'$')), % at least one $ has been found
  3131.                         answer=true;
  3132.                         break
  3133.                     end
  3134.                 end
  3135.             else % just one line
  3136.                 if ~isempty(strfind(textin{ii},'$')), % at least one $ has been found
  3137.                     answer=true;
  3138.                     break
  3139.                 end
  3140.             end
  3141.            
  3142.         end
  3143.     end
  3144.  
  3145. % FUNCTION CONVERT_TEXT_TO_LATEX
  3146. %
  3147. %    textout = convert_text_to_line(textin)
  3148. %
  3149. %       textin  - normal text to be converted to proper latex code
  3150. %
  3151. %       textout - converted text
  3152. %
  3153. %  COPY OF MATFIG2PGF
  3154. %
  3155. %--------------------------------------------------------------------------
  3156.     function textout = convert_text_to_latex(textin)
  3157.         textcell=textin;
  3158.         % test if textin is a cell array
  3159.         if ~iscell(textin), textcell={textin}; end % convert
  3160.         textoutCell=textcell;
  3161.         for jj=1:length(textcell),
  3162.             textin=textcell{jj};
  3163.             if iscell(textin), % still a cell, means multiple lines
  3164.                 for kk=1:length(textin)
  3165.                     textout{kk}=doTheConversion(textin{kk});
  3166.                 end
  3167.                 textoutCell{jj}=textout;
  3168.             else
  3169.                 textout=doTheConversion(textin);
  3170.                 textoutCell{jj}=textout;
  3171.             end
  3172.         end
  3173.        
  3174.         if length(textcell)==1,
  3175.             textout=textoutCell{1};
  3176.         else
  3177.             textout=textoutCell;
  3178.         end
  3179.        
  3180.         %-- end of function convert_text_to_latex ---------------------------------
  3181.        
  3182.        
  3183.         function textout=doTheConversion(textin)
  3184.             % textin
  3185.            
  3186.             % Split strings in groups separated by space and/or }[a-z]
  3187.             splitStrings = {};
  3188.             i = 1;
  3189.             thisStartIndex = 1;
  3190.             while i <= length(textin),
  3191.                 if ~isempty(regexp(textin(i), '\s', 'once'))
  3192.                     splitStrings{length(splitStrings)+1} = textin(thisStartIndex:i);
  3193.                     thisStartIndex = i+1;
  3194.                 elseif (i < length(textin)) && ~isempty(regexpi(textin(i:i+1), '}[a-z]', 'once'))
  3195.                     splitStrings{length(splitStrings)+1} = textin(thisStartIndex:i);
  3196.                     thisStartIndex = i+1;
  3197.                 elseif (i < length(textin)) && ~isempty(regexpi(textin(i:i+1), '[^_\^]{'))
  3198.                     splitStrings{length(splitStrings)+1} = textin(thisStartIndex:i);
  3199.                     thisStartIndex = i+1;
  3200.                 elseif i == length(textin)
  3201.                     % Last character of string
  3202.                     splitStrings{length(splitStrings)+1} = textin(thisStartIndex:i);
  3203.                 end
  3204.                 i = i+1;
  3205.             end
  3206.            
  3207.             % If two consecutive strings need to set in mathmode and have no whitespace
  3208.             % in between. They must be joined to one math mode string.
  3209.             newSplitStrings = {};
  3210.             for i = 1:length(splitStrings)
  3211.                 if i > 1
  3212.                     prev = newSplitStrings{length(newSplitStrings)};
  3213.                     next = splitStrings{i};
  3214.                     if inMathMode(prev) && inMathMode(next)
  3215.                         if isempty(regexp(prev(end), '\s', 'once')) && isempty(regexp(next(1), '\s', 'once'))
  3216.                             newSplitStrings{length(newSplitStrings)} = [prev next];
  3217.                         else
  3218.                             newSplitStrings{length(newSplitStrings)+1} = next;
  3219.                         end
  3220.                     else
  3221.                         newSplitStrings{length(newSplitStrings)+1} = next;
  3222.                     end
  3223.                 else
  3224.                     newSplitStrings{length(newSplitStrings)+1} = splitStrings{i};
  3225.                 end
  3226.             end
  3227.             splitStrings = newSplitStrings;
  3228.            
  3229.             textout = '';
  3230.             for i = 1:length(splitStrings)
  3231.                 if iscell(splitStrings{i}), % not sure if this is the right way
  3232.                     splitStrings{i}=splitStrings{i}{1};
  3233.                 end
  3234.                 if ~inMathMode(splitStrings{i})
  3235.                     textout = [textout splitStrings{i}];
  3236.                 else
  3237.                     thisString = splitStrings{i};
  3238.                    
  3239.                     % Remove whitespace at end of string
  3240.                     lastIndex = length(thisString)+1-regexp(fliplr(thisString), '[^\s]', 'once');
  3241.                     if lastIndex < length(thisString)
  3242.                         trailingWhitespace = true;
  3243.                         thisString = thisString(1:lastIndex);
  3244.                     else
  3245.                         trailingWhitespace = false;
  3246.                     end
  3247.                    
  3248.                     % If the are acculades at the beginning and end they can be removed
  3249.                     if strcmp(thisString(1), '{') && strcmp(thisString(lastIndex), '}')
  3250.                         thisString = thisString(2:lastIndex-1);
  3251.                     end
  3252.                    
  3253.                     textout = [textout '$' thisString '$'];
  3254.                     if trailingWhitespace
  3255.                         textout = [textout ' '];
  3256.                     end
  3257.                 end
  3258.             end
  3259.            
  3260.             % Replace % signs in the text because they are comments in latex
  3261.             textout = regexprep(textout, '%', '\\%');
  3262.         end
  3263.        
  3264.        
  3265.     end
  3266.  
  3267. % FUNCTION INMATHMODE
  3268. %
  3269. % Determines whether a string needs to be typeset in math mode in LaTeX
  3270. %
  3271. % [ mathmode ] = inMathMode( str )
  3272. %
  3273. %  str - string that needs to be checked
  3274. %
  3275. %  mathmode - True when it needs to be typeset in math mode, return false
  3276. %             when it should be typeset in normal text mode.
  3277. %
  3278. %  COPY OF MATFIG2PGF
  3279. %
  3280.     function [ mathmode ] = inMathMode( str )
  3281.         mathmode = ~isempty(regexp(str, '[|\\_\^]', 'once'));
  3282.         %-- end of function inmathmode --------------------------------------------
  3283.     end
  3284.  
  3285.  
  3286.  
  3287.  
  3288.  
  3289.     function labels_out = convert_TickLabels2Cell (ticks, labels)
  3290.         labels_out = {};
  3291.         if length (ticks) == size (labels, 1), % same size
  3292.            
  3293.             if ~ iscell (labels)
  3294.                 for ii = 1 : size (labels, 1)
  3295.                     labels_out{ii} = labels(ii, :);
  3296.                 end
  3297.             else
  3298.                 labels_out = labels;
  3299.             end
  3300.            
  3301.         else % not the same size
  3302.            
  3303.             if ~isempty(ticks) && isempty(labels), % ticks but no labels,
  3304.                
  3305.                 for ii = 1 : length (ticks)
  3306.                     labels_out{ii} = '';% empty label
  3307.                 end
  3308.                
  3309.             else % not same size but
  3310.    
  3311.                 reps = ceil (length (ticks) / size (labels, 1));
  3312.                
  3313.                 if ~ iscell (labels)
  3314.                    
  3315.                     labels = repmat (labels, reps, 1); % repeat labels
  3316.                     for ii = 1 : length (ticks)
  3317.                         labels_out{ii} = labels(ii, :);
  3318.                     end
  3319.                 else
  3320.                     labels = repmat (labels, reps, 1); % repeat labels
  3321.                     for ii = 1 : length (ticks)
  3322.                         labels_out{ii} = labels{ii};
  3323.                     end
  3324.                 end
  3325.             end
  3326.            
  3327.         end
  3328.     end
  3329.  
  3330. end
  3331.  
  3332.  
  3333.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement