Advertisement
adn

fig2texps

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