-
Notifications
You must be signed in to change notification settings - Fork 0
/
matlab2tikz.m
5460 lines (4963 loc) · 217 KB
/
matlab2tikz.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function matlab2tikz(varargin)
%MATLAB2TIKZ Save figure in native LaTeX (TikZ/Pgfplots).
% MATLAB2TIKZ() saves the current figure as LaTeX file.
% MATLAB2TIKZ comes with several options that can be combined at will.
%
% MATLAB2TIKZ(FILENAME,...) or MATLAB2TIKZ('filename',FILENAME,...)
% stores the LaTeX code in FILENAME.
%
% MATLAB2TIKZ('filehandle',FILEHANDLE,...) stores the LaTeX code in the file
% referenced by FILEHANDLE. (default: [])
%
% MATLAB2TIKZ('figurehandle',FIGUREHANDLE,...) explicitly specifies the
% handle of the figure that is to be stored. (default: gcf)
%
% MATLAB2TIKZ('colormap',DOUBLE,...) explicitly specifies the colormap to be
% used. (default: current color map)
%
% MATLAB2TIKZ('strict',BOOL,...) tells MATLAB2TIKZ to adhere to MATLAB(R)
% conventions wherever there is room for relaxation. (default: false)
%
% MATLAB2TIKZ('strictFontSize',BOOL,...) retains the exact font sizes
% specified in MATLAB for the TikZ code. This goes against normal LaTeX
% practice. (default: false)
%
% MATLAB2TIKZ('showInfo',BOOL,...) turns informational output on or off.
% (default: true)
%
% MATLAB2TIKZ('showWarning',BOOL,...) turns warnings on or off.
% (default: true)
%
% MATLAB2TIKZ('imagesAsPng',BOOL,...) stores MATLAB(R) images as (lossless)
% PNG files. This is more efficient than storing the image color data as TikZ
% matrix. (default: true)
%
% MATLAB2TIKZ('externalData',BOOL,...) stores all data points in external
% files as tab separated values (TSV files). (default: false)
%
% MATLAB2TIKZ('relativeDataPath',CHAR, ...) tells MATLAB2TIKZ to use the
% given path to follow the external data files and PNG files. If LaTeX
% source and the external files will reside in the same directory, this can
% be set to '.'. (default: [])
%
% MATLAB2TIKZ('height',CHAR,...) sets the height of the image. This can be
% any LaTeX-compatible length, e.g., '3in' or '5cm' or '0.5\textwidth'. If
% unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('width',CHAR,...) sets the width of the image.
% If unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('extraCode',CHAR or CELLCHAR,...) explicitly adds extra code
% at the beginning of the output file. (default: [])
%
% MATLAB2TIKZ('extraCodeAtEnd',CHAR or CELLCHAR,...) explicitly adds extra
% code at the end of the output file. (default: [])
%
% MATLAB2TIKZ('extraAxisOptions',CHAR or CELLCHAR,...) explicitly adds extra
% options to the Pgfplots axis environment. (default: [])
%
% MATLAB2TIKZ('extraColors', {{'name',[R G B]}, ...} , ...) adds
% user-defined named RGB-color definitions to the TikZ output.
% R, G and B are expected between 0 and 1. (default: {})
%
% MATLAB2TIKZ('extraTikzpictureOptions',CHAR or CELLCHAR,...)
% explicitly adds extra options to the tikzpicture environment. (default: [])
%
% MATLAB2TIKZ('encoding',CHAR,...) sets the encoding of the output file.
%
% MATLAB2TIKZ('floatFormat',CHAR,...) sets the format used for float values.
% You can use this to decrease the file size. (default: '%.15g')
%
% MATLAB2TIKZ('maxChunkLength',INT,...) sets maximum number of data points
% per \addplot for line plots (default: 4000)
%
% MATLAB2TIKZ('parseStrings',BOOL,...) determines whether title, axes labels
% and the like are parsed into LaTeX by MATLAB2TIKZ's parser.
% If you want greater flexibility, set this to false and use straight LaTeX
% for your labels. (default: true)
%
% MATLAB2TIKZ('parseStringsAsMath',BOOL,...) determines whether to use TeX's
% math mode for more characters (e.g. operators and figures). (default: false)
%
% MATLAB2TIKZ('showHiddenStrings',BOOL,...) determines whether to show
% strings whose were deliberately hidden. This is usually unnecessary, but
% can come in handy for unusual plot types (e.g., polar plots). (default:
% false)
%
% MATLAB2TIKZ('interpretTickLabelsAsTex',BOOL,...) determines whether to
% interpret tick labels as TeX. MATLAB(R) doesn't do that by default.
% (default: false)
%
% MATLAB2TIKZ('tikzFileComment',CHAR,...) adds a custom comment to the header
% of the output file. (default: '')
%
% MATLAB2TIKZ('automaticLabels',BOOL,...) determines whether to automatically
% add labels to plots (where applicable) which make it possible to refer
% to them using \ref{...} (e.g., in the caption of a figure). (default: false)
%
% MATLAB2TIKZ('standalone',BOOL,...) determines whether to produce
% a standalone compilable LaTeX file. Setting this to true may be useful for
% taking a peek at what the figure will look like. (default: false)
%
% MATLAB2TIKZ('checkForUpdates',BOOL,...) determines whether to automatically
% check for updates of matlab2tikz. (default: true)
%
% Example
% x = -pi:pi/10:pi;
% y = tan(sin(x)) - sin(tan(x));
% plot(x,y,'--rs');
% matlab2tikz('myfile.tex');
%
% Copyright (c) 2008--2014, Nico Schlömer <[email protected]>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% Note:
% This program is originally based on Paul Wagenaars' Matfig2PGF which itself
% uses pure PGF as output format <[email protected]>, see
%
% http://www.mathworks.com/matlabcentral/fileexchange/12962
%
% In an attempt to simplify and extend things, the idea for matlab2tikz has
% emerged. The goal is to provide the user with a clean interface between the
% very handy figure creation in MATLAB and the powerful means that TikZ with
% Pgfplots has to offer.
%
% =========================================================================
% Check if we are in MATLAB or Octave.
[m2t.env, m2t.envVersion] = getEnvironment();
minimalVersion = struct('MATLAB', struct('name','2008b', 'num',[7 7]), ...
'Octave', struct('name','3.4.0', 'num',[3 4 0]));
checkDeprecatedEnvironment(m2t, minimalVersion);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m2t.cmdOpts = [];
m2t.currentHandles = [];
% For hgtransform groups.
m2t.transform = [];
m2t.pgfplotsVersion = [1,3];
m2t.name = 'matlab2tikz';
m2t.version = '0.4.7';
m2t.author = 'Nico Schlömer';
m2t.authorEmail = '[email protected]';
m2t.years = '2008--2014';
m2t.website = 'http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz';
VCID = VersionControlIdentifier();
m2t.versionFull = strtrim(sprintf('v%s %s', m2t.version, VCID));
m2t.tol = 1.0e-15; % global round-off tolerance;
% used, for example, in equality test for doubles
m2t.imageAsPngNo = 0;
m2t.dataFileNo = 0;
% definition of color depth
m2t.colorDepth = 48; %[bit] RGB color depth (typical values: 24, 30, 48)
m2t.colorPrecision = 2^(-m2t.colorDepth/3);
m2t.colorFormat = sprintf('%%0.%df',ceil(-log10(m2t.colorPrecision)));
% the actual contents of the TikZ file go here
m2t.content = struct('name', [], ...
'comment', [], ...
'options', {cell(0,2)}, ...
'content', {cell(0)}, ...
'children', {cell(0)} ...
);
m2t.preamble = sprintf(['\\usepackage{pgfplots}\n', ...
'\\usepackage{grffile}\n', ...
'\\pgfplotsset{compat=newest}\n', ...
'\\usetikzlibrary{plotmarks}\n', ...
'\\usepackage{amsmath}\n']);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% scan the options
ipp = matlab2tikzInputParser;
ipp = ipp.addOptional(ipp, 'filename', [], @(x) filenameValidation(x,ipp));
ipp = ipp.addOptional(ipp, 'filehandle', [], @filehandleValidation);
ipp = ipp.addParamValue(ipp, 'figurehandle', get(0,'CurrentFigure'), @ishandle);
ipp = ipp.addParamValue(ipp, 'colormap', [], @isnumeric);
ipp = ipp.addParamValue(ipp, 'strict', false, @islogical);
ipp = ipp.addParamValue(ipp, 'strictFontSize', false, @islogical);
ipp = ipp.addParamValue(ipp, 'showInfo', true, @islogical);
ipp = ipp.addParamValue(ipp, 'showWarnings', true, @islogical);
ipp = ipp.addParamValue(ipp, 'checkForUpdates', true, @islogical);
ipp = ipp.addParamValue(ipp, 'encoding' , '', @ischar);
ipp = ipp.addParamValue(ipp, 'standalone', false, @islogical);
ipp = ipp.addParamValue(ipp, 'tikzFileComment', '', @ischar);
ipp = ipp.addParamValue(ipp, 'extraColors', {}, @iscolordefinitions);
ipp = ipp.addParamValue(ipp, 'extraCode', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraCodeAtEnd', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraAxisOptions', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraTikzpictureOptions', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'floatFormat', '%.15g', @ischar);
ipp = ipp.addParamValue(ipp, 'automaticLabels', false, @islogical);
ipp = ipp.addParamValue(ipp, 'showHiddenStrings', false, @islogical);
ipp = ipp.addParamValue(ipp, 'height', [], @ischar);
ipp = ipp.addParamValue(ipp, 'width' , [], @ischar);
ipp = ipp.addParamValue(ipp, 'imagesAsPng', true, @islogical);
ipp = ipp.addParamValue(ipp, 'externalData', false, @islogical);
ipp = ipp.addParamValue(ipp, 'relativeDataPath', [], @ischar);
% Maximum chunk length.
% TeX parses files line by line with a buffer of size buf_size. If the
% plot has too many data points, pdfTeX's buffer size may be exceeded.
% As a work-around, the plot is split into several smaller plots, and this
% function does the job.
%
% What is a "large" array?
% TeX parser buffer is buf_size=200000 char on Mac TeXLive, let's say
% 100000 to be on the safe side.
% 1 point is represented by 25 characters (estimation): 2 coordinates (10
% char), 2 brackets, commma and white space, + 1 extra char.
% That gives a magic arbitrary number of 4000 data points per array.
ipp = ipp.addParamValue(ipp, 'maxChunkLength', 4000, @isnumeric);
% By default strings like axis labels are parsed to match the appearance of
% strings as closely as possible to that generated by MATLAB.
% If the user wants to have particular strings in the matlab2tikz output that
% can't be generated in MATLAB, they can disable string parsing. In that case
% all strings are piped literally to the LaTeX output.
ipp = ipp.addParamValue(ipp, 'parseStrings', true, @islogical);
% In addition to regular string parsing, an additional stage can be enabled
% which uses TeX's math mode for more characters like figures and operators.
ipp = ipp.addParamValue(ipp, 'parseStringsAsMath', false, @islogical);
% As opposed to titles, axis labels and such, MATLAB(R) does not interpret tick
% labels as TeX. matlab2tikz retains this behavior, but if it is desired to
% interpret the tick labels as TeX, set this option to true.
ipp = ipp.addParamValue(ipp, 'interpretTickLabelsAsTex', false, @islogical);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% deprecated parameters (will auto-generate warnings upon parse)
ipp = ipp.addParamValue(ipp, 'relativePngPath', [], @ischar);
ipp = ipp.deprecateParam(ipp, 'relativePngPath', 'relativeDataPath');
% Finally parse all the elements.
ipp = ipp.parse(ipp, varargin{:});
m2t.cmdOpts = ipp; % store the input parser back into the m2t data struct
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% inform users of potentially dangerous options
if m2t.cmdOpts.Results.parseStringsAsMath
userInfo(m2t, ['\n==========================================================================\n', ...
'You are using the parameter ''parseStringsAsMath''.\n', ...
'This may produce undesirable string output. For full control over output\n', ...
'strings please set the parameter ''parseStrings'' to false.\n', ...
'==========================================================================']);
end
% The following color RGB-values which will need to be defined.
% 'extraRgbColorNames' contains their designated names, 'extraRgbColorSpecs'
% their specifications.
[m2t.extraRgbColorNames, m2t.extraRgbColorSpecs] = ...
dealColorDefinitions(m2t.cmdOpts.Results.extraColors);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% shortcut
m2t.ff = m2t.cmdOpts.Results.floatFormat;
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% add global elements
if isempty(m2t.cmdOpts.Results.figurehandle)
error('matlab2tikz:figureNotFound','MATLAB figure not found.');
end
m2t.currentHandles.gcf = m2t.cmdOpts.Results.figurehandle;
if m2t.cmdOpts.Results.colormap
m2t.currentHandles.colormap = m2t.cmdOpts.Results.colormap;
else
m2t.currentHandles.colormap = get(m2t.currentHandles.gcf, 'colormap');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle output file handle/file name
if ~isempty(m2t.cmdOpts.Results.filehandle)
fid = m2t.cmdOpts.Results.filehandle;
fileWasOpen = true;
if ~isempty(m2t.cmdOpts.Results.filename)
userWarning(m2t, ...
'File handle AND file name for output given. File handle used, file name discarded.')
end
else
fileWasOpen = false;
% set filename
if ~isempty(m2t.cmdOpts.Results.filename)
filename = m2t.cmdOpts.Results.filename;
else
[filename, pathname] = uiputfile({'*.tex;*.tikz'; '*.*'}, 'Save File');
filename = fullfile(pathname, filename);
end
% open the file for writing
fid = fileOpenForWrite(m2t, filename);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m2t.tikzFileName = fopen(fid);
if m2t.cmdOpts.Results.automaticLabels
m2t.automaticLabelIndex = 0;
end
% By default, reference the PNG (if required) from the TikZ file
% as the file path of the TikZ file itself. This works if the MATLAB script
% is executed in the same folder where the TeX file sits.
if isempty(m2t.cmdOpts.Results.relativeDataPath)
if ~isempty(m2t.cmdOpts.Results.relativePngPath)
%NOTE: eventually break backwards compatibility of relative PNG path
m2t.relativeDataPath = m2t.cmdOpts.Results.relativePngPath;
userWarning(m2t, ['Using "relativePngPath" for "relativeDataPath".', ...
' This will stop working in a future release.']);
else
m2t.relativeDataPath = fileparts(m2t.tikzFileName);
end
else
m2t.relativeDataPath = m2t.cmdOpts.Results.relativeDataPath;
end
userInfo(m2t, ['(To disable info messages, pass [''showInfo'', false] to matlab2tikz.)\n', ...
'(For all other options, type ''help matlab2tikz''.)\n']);
userInfo(m2t, '\nThis is %s %s.\n', m2t.name, m2t.versionFull)
% Conditionally check for a new matlab2tikz version outside version control
if m2t.cmdOpts.Results.checkForUpdates && isempty(VCID)
updater(m2t.name, ...
m2t.website, ...
m2t.version, ...
m2t.cmdOpts.Results.showInfo, ...
m2t.env)
end
% print some version info to the screen
versionInfo = ['The latest updates can be retrieved from\n' ,...
' %s\n' ,...
'where you can also make suggestions and rate %s.\n' ,...
'For usage instructions, bug reports, the latest ' ,...
'development versions and more, see\n' ,...
' https://github.com/nschloe/matlab2tikz,\n' ,...
' https://github.com/nschloe/matlab2tikz/wiki,\n' ,...
' https://github.com/nschloe/matlab2tikz/issues.\n'
];
userInfo(m2t, versionInfo, m2t.website, m2t.name);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Save the figure as pgf to file -- here's where the work happens
saveToFile(m2t, fid, fileWasOpen);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
end
% =========================================================================
function l = filenameValidation(x, p)
% is the filename argument NOT another keyword?
l = ischar(x) && ~any(strcmp(x,p.Parameters));
end
% =========================================================================
function l = filehandleValidation(x)
% is the filehandle the handle to an opened file?
l = isnumeric(x) && any(x==fopen('all'));
end
% =========================================================================
function l = isCellOrChar(x)
l = iscell(x) || ischar(x);
end
% =========================================================================
function isValid = iscolordefinitions(colors)
isRGBTuple = @(c)( numel(c) == 3 && all(0<=c & c<=1) );
isValidEntry = @(e)( iscell(e) && ischar(e{1}) && isRGBTuple(e{2}) );
isValid = iscell(colors) && all(cellfun(isValidEntry, colors));
end
%==========================================================================
function fid = fileOpenForWrite(m2t, filename)
switch m2t.env
case 'MATLAB'
fid = fopen(filename, ...
'w', ...
'native', ...
m2t.cmdOpts.Results.encoding ...
);
case 'Octave'
fid = fopen(filename, 'w');
otherwise
errorUnknownEnvironment();
end
if fid == -1
error('matlab2tikz:fileOpenError', ...
'Unable to open file ''%s'' for writing.', ...
filename);
end
end
%==========================================================================
function path = TeXpath(path)
path = strrep(path, filesep, '/');
% TeX uses '/' as a file separator (as UNIX). Windows, however, uses
% '\' which is not supported by TeX as a file separator
end
% =========================================================================
function m2t = saveToFile(m2t, fid, fileWasOpen)
% Save the figure as TikZ to a file.
% All other routines are called from here.
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% enter plot recursion --
% It is important to turn hidden handles on, as visible lines (such as the
% axes in polar plots, for example), are otherwise hidden from their
% parental handles (and can hence not be discovered by matlab2tikz).
% With ShowHiddenHandles 'on', there is no escape. :)
set(0, 'ShowHiddenHandles', 'on');
% get all axes handles
fh = m2t.currentHandles.gcf;
axesHandles = findobj(fh, 'type', 'axes');
tagKeyword = switchMatOct(m2t, 'Tag', 'tag');
if ~isempty(axesHandles)
% Find all legend handles. This is MATLAB-only.
legendHandleIdx = strcmp(get(axesHandles, tagKeyword), 'legend');
m2t.legendHandles = axesHandles(legendHandleIdx);
% Remove all legend handles as they are treated separately.
axesHandles = axesHandles(~legendHandleIdx);
end
colorbarKeyword = switchMatOct(m2t, 'Colorbar', 'colorbar');
if ~isempty(axesHandles)
% Find all colorbar handles. This is MATLAB-only.
cbarHandleIdx = strcmp(get(axesHandles, tagKeyword), colorbarKeyword);
m2t.cbarHandles = axesHandles(cbarHandleIdx);
% Remove all legend handles as they are treated separately.
axesHandles = axesHandles(~cbarHandleIdx);
else
m2t.cbarHandles = [];
end
% Turn around the handles vector to make sure that plots that appeared
% first also appear first in the vector. This has effects on the alignment
% and the order in which the plots appear in the final TikZ file.
% In fact, this is not really important but makes things more 'natural'.
axesHandles = axesHandles(end:-1:1);
% find alignments
[relevantAxesHandles, alignmentOptions, IX] = alignSubPlots(m2t, axesHandles);
m2t.axesContainers = {};
for ix = IX(:)'
m2t = drawAxes(m2t, relevantAxesHandles(ix), alignmentOptions(ix));
end
% Handle color bars.
for cbar = m2t.cbarHandles(:)'
m2t = handleColorbar(m2t, cbar);
end
% Add all axes containers to the file contents.
for axesContainer = m2t.axesContainers
m2t.content = addChildren(m2t.content, axesContainer);
end
set(0, 'ShowHiddenHandles', 'off');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% actually print the stuff
minimalPgfplotsVersion = formatPgfplotsVersion(m2t, m2t.pgfplotsVersion);
environment = sprintf('%s %s',m2t.env, m2t.envVersion);
m2t.content.comment = sprintf(['This file was created by %s %s running on %s.\n', ...
'Copyright (c) %s, %s <%s>\n', ...
'All rights reserved.\n',...
'Minimal pgfplots version: %s\n'], ...
m2t.name, m2t.versionFull, environment, ...
m2t.years, m2t.author, m2t.authorEmail,...
minimalPgfplotsVersion);
if m2t.cmdOpts.Results.showInfo
% disable this info if showInfo=false
m2t.content.comment = [m2t.content.comment, ...
sprintf(['\n',...
'The latest updates can be retrieved from\n', ...
' %s\n', ...
'where you can also make suggestions and rate %s.\n'], ...
m2t.website, m2t.name ) ...
];
end
userInfo(m2t, 'You will need pgfplots version %s or newer to compile the TikZ output.',...
minimalPgfplotsVersion);
% Add custom comment.
if ~isempty(m2t.cmdOpts.Results.tikzFileComment)
m2t.content.comment = [m2t.content.comment, ...
sprintf('\n%s\n', m2t.cmdOpts.Results.tikzFileComment)
];
end
m2t.content.name = 'tikzpicture';
% Add custom TikZ options if any given.
if ~isempty(m2t.cmdOpts.Results.extraTikzpictureOptions)
if ischar(m2t.cmdOpts.Results.extraTikzpictureOptions)
m2t.cmdOpts.Results.extraTikzpictureOptions = ...
{m2t.cmdOpts.Results.extraTikzpictureOptions};
end
for k = 1:length(m2t.cmdOpts.Results.extraTikzpictureOptions)
m2t.content.options = ...
addToOptions(m2t.content.options, ...
m2t.cmdOpts.Results.extraTikzpictureOptions{k}, []);
end
end
% Don't forget to define the colors.
if ~isempty(m2t.extraRgbColorNames)
m2t.content.colors = sprintf('%%\n%% defining custom colors\n');
for k = 1:length(m2t.extraRgbColorNames)
% make sure to append with '%' to avoid spacing woes
ff = m2t.colorFormat;
m2t.content.colors = [m2t.content.colors, ...
sprintf(['\\definecolor{%s}{rgb}{', ff, ',', ff, ',', ff,'}%%\n'], ...
m2t.extraRgbColorNames{k}', m2t.extraRgbColorSpecs{k})];
end
m2t.content.colors = [m2t.content.colors sprintf('%%\n')];
end
% Finally print it to the file,
if ~isempty(m2t.content.comment)
fprintf(fid, '%% %s\n', ...
strrep(m2t.content.comment, sprintf('\n'), sprintf('\n%% ')));
end
if m2t.cmdOpts.Results.standalone
fprintf(fid, '\\documentclass[tikz]{standalone}\n%s\n', m2t.preamble);
end
addCustomCode(fid, '', m2t.cmdOpts.Results.extraCode);
if m2t.cmdOpts.Results.standalone
fprintf(fid, '\\begin{document}\n');
end
% printAll() handles the actual figure plotting.
printAll(m2t, m2t.content, fid);
addCustomCode(fid, '\n', m2t.cmdOpts.Results.extraCodeAtEnd);
if m2t.cmdOpts.Results.standalone
fprintf(fid, '\n\\end{document}');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% close the file if necessary
if ~fileWasOpen
fclose(fid);
end
end
% =========================================================================
function addCustomCode(fid, before, code)
if ~isempty(code)
fprintf(fid, before);
if ischar(code)
code = {code};
end
if iscellstr(code)
for str = code(:)'
fprintf(fid, '%s\n', str{1});
end
else
error('matlab2tikz:saveToFile', 'Need str or cellstr.');
end
fprintf(fid,after);
end
end
% =========================================================================
function [m2t, pgfEnvironments] = handleAllChildren(m2t, handle)
% Draw all children of a graphics object (if they need to be drawn).
children = get(handle, 'Children');
% prepare cell array of pgfEnvironments
pgfEnvironments = cell(0);
% It's important that we go from back to front here, as this is
% how MATLAB does it, too. Significant for patch (contour) plots,
% and the order of plotting the colored patches.
for child = children(end:-1:1)'
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% First of all, check if 'child' is referenced in a legend.
% If yes, some plot types may want to add stuff (e.g. 'forget plot').
% Add '\addlegendentry{...}' then after the plot.
legendString = [];
m2t.currentHandleHasLegend = false;
% Check if current handle is referenced in a legend.
switch m2t.env
case 'MATLAB'
if ~isempty(m2t.legendHandles)
% Make sure that m2t.legendHandles is a row vector.
for legendHandle = m2t.legendHandles(:)'
ud = get(legendHandle, 'UserData');
% In Octave, the field name is 'handle'. Well, whatever.
% fieldName = switchMatOct(m2t, 'handles', 'handle');
k = find(child == ud.handles);
if isempty(k)
% Lines of error bar plots are not referenced
% directly in legends as an error bars plot contains
% two "lines": the data and the deviations. Here, the
% legends refer to the specgraph.errorbarseries
% handle which is 'Parent' to the line handle.
k = find(get(child,'Parent') == ud.handles);
end
if ~isempty(k)
% Legend entry found. Add it to the plot.
m2t.currentHandleHasLegend = true;
interpreter = get(legendHandle, 'Interpreter');
legendString = ud.lstrings(k);
end
end
end
case 'Octave'
% Octave associates legends with axes, not with (line) plot.
% The variable m2t.gcaHasLegend is set in drawAxes().
m2t.currentHandleHasLegend = ~isempty(m2t.gcaAssociatedLegend);
interpreter = get(m2t.gcaAssociatedLegend, 'interpreter');
if isfield(get(child), 'displayname')
legendString = get(child, 'displayname');
end
otherwise
errorUnknownEnvironment();
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
switch get(child, 'Type')
% 'axes' environments are treated separately.
case 'line'
[m2t, str] = drawLine(m2t, child);
case 'patch'
[m2t, str] = drawPatch(m2t, child);
case 'image'
[m2t, str] = drawImage(m2t, child);
case 'hggroup'
[m2t, str] = drawHggroup(m2t, child);
case 'hgtransform'
% From http://www.mathworks.de/de/help/matlab/ref/hgtransformproperties.html:
% Matrix: 4-by-4 matrix
% Transformation matrix applied to hgtransform object and its
% children. The hgtransform object applies the transformation
% matrix to all its children.
% More information at http://www.mathworks.de/de/help/matlab/creating_plots/group-objects.html.
m2t.transform = get(child, 'Matrix');
[m2t, str] = handleAllChildren(m2t, child);
m2t.transform = [];
case 'surface'
[m2t, str] = drawSurface(m2t, child);
case 'text'
[m2t, str] = drawText(m2t, child);
case 'rectangle'
[m2t, str] = drawRectangle(m2t, child);
case {'uitoolbar', 'uimenu', 'uicontextmenu', 'uitoggletool',...
'uitogglesplittool', 'uipushtool', 'hgjavacomponent'}
% don't to anything for these handles and its children
str = [];
otherwise
error('matlab2tikz:handleAllChildren', ...
'I don''t know how to handle this object: %s\n', ...
get(child, 'Type'));
end
% Add legend after the plot data.
% The test for ischar(str) && ~isempty(str) is a workaround for hggroups;
% the output might not necessarily be a string, but a cellstr.
if ischar(str) && ~isempty(str) ...
&& m2t.currentHandleHasLegend && ~isempty(legendString)
c = prettyPrint(m2t, legendString, interpreter);
% We also need a legend alignment option to make multiline
% legend entries work. This is added by default in getLegendOpts().
str = [str, ...
sprintf('\\addlegendentry{%s};\n\n', join(m2t, c, '\\'))]; %#ok
end
% append the environment
pgfEnvironments{end+1} = str;
end
end
% =========================================================================
function data = applyHgTransform(m2t, data)
if ~isempty(m2t.transform)
R = m2t.transform(1:3,1:3);
t = m2t.transform(1:3,4);
n = size(data, 1);
data = data * R' ...
+ kron(ones(n,1), t');
end
end
% =========================================================================
function m2t = drawAxes(m2t, handle, alignmentOptions)
% Input arguments:
% handle.................The axes environment handle.
% alignmentOptions.......The alignment options as defined in the
% function 'alignSubPlots()'.
% This argument is optional.
% Handle special cases.
% MATLAB(R) uses 'Tag', Octave 'tag' for their tags. :/
tagKeyword = switchMatOct(m2t, 'Tag', 'tag');
colorbarKeyword = switchMatOct(m2t, 'Colorbar', 'colorbar');
switch get(handle, tagKeyword)
case colorbarKeyword
% Handle a colorbar separately.
m2t = handleColorbar(m2t, handle);
return
case 'legend'
% Don't handle the legend here, but further below in the 'axis'
% environment.
% In MATLAB, an axes environment and its corresponding legend are
% children of the same figure (siblings), while in Pgfplots, the
% \legend (or \addlegendentry) command must appear within the axis
% environment.
return
otherwise
% continue as usual
end
% Initialize empty enviroment.
% Use a struct instead of a custom subclass of hgsetget (which would
% facilitate writing clean code) as structs are more portable (old MATLAB(R)
% versions, GNU Octave).
m2t.axesContainers{end+1} = struct('handle', handle, ...
'name', [], ...
'comment', [], ...
'options', {cell(0,2)}, ...
'content', {cell(0)}, ...
'children', {cell(0)}, ...
'stackedBarsPresent', false, ...
'nonbarPlotsPresent', false ...
);
% update gca
m2t.currentHandles.gca = handle;
% This is an ugly workaround for bar plots.
% Bar plots need to have several values counted on a per-axes basis, e.g.,
% the number of bars. Setting m2t.barplotId to [] here makes sure those
% values are recomputed in drawBarseries().
m2t.barplotId = [];
% Octave:
% Check if this axis environment is referenced by a legend.
m2t.gcaAssociatedLegend = [];
switch m2t.env
case 'Octave'
if ~isempty(m2t.legendHandles)
% Make sure that m2t.legendHandles is a row vector.
for lhandle = m2t.legendHandles(:)'
ud = get(lhandle, 'UserData');
if any(handle == ud.handle)
m2t.gcaAssociatedLegend = lhandle;
break;
end
end
end
case 'MATLAB'
% no action needed
otherwise
errorUnknownEnvironment();
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get the axes dimensions
dim = getAxesDimensions(handle, ...
m2t.cmdOpts.Results.width, ...
m2t.cmdOpts.Results.height);
% set the width
if dim.x.unit(1)=='\' && dim.x.value==1.0
% only return \figurewidth instead of 1.0\figurewidth
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, 'width', dim.x.unit);
else
if strcmp(dim.x.unit, 'px')
% TikZ doesn't know pixels. -- Convert to inches.
dpi = get(0, 'ScreenPixelsPerInch');
dim.x.value = dim.x.value / dpi;
dim.x.unit = 'in';
end
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, 'width', ...
sprintf([m2t.ff, '%s'], dim.x.value, dim.x.unit));
end
if dim.y.unit(1)=='\' && dim.y.value==1.0
% only return \figureheight instead of 1.0\figureheight
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, 'height', dim.y.unit);
else
if strcmp(dim.y.unit, 'px')
% TikZ doesn't know pixels. -- Convert to inches.
dpi = get(0, 'ScreenPixelsPerInch');
dim.y.value = dim.y.value / dpi;
dim.y.unit = 'in';
end
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, 'height', ...
sprintf([m2t.ff, '%s'], dim.y.value, dim.y.unit));
end
% Add the physical dimension of one unit of length in the coordinate system.
% This is used later on to translate lenghts to physical units where
% necessary (e.g., in bar plots).
m2t.unitlength.x.unit = dim.x.unit;
xLim = get(m2t.currentHandles.gca, 'XLim');
m2t.unitlength.x.value = dim.x.value / (xLim(2)-xLim(1));
m2t.unitlength.y.unit = dim.y.unit;
yLim = get(m2t.currentHandles.gca, 'YLim');
m2t.unitlength.y.value = dim.y.value / (yLim(2)-yLim(1));
for axis = 'xyz'
m2t.([axis 'AxisReversed']) = ...
strcmp(get(handle,[upper(axis),'Dir']), 'reverse');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% In MATLAB, all plots are treated as 3D plots; it's just the view that
% makes 2D plots appear like 2D.
% Recurse into the children of this environment. Do this here to give the
% contained plots the chance to set m2t.currentAxesContain3dData to true.
m2t.currentAxesContain3dData = false;
[m2t, childrenEnvs] = handleAllChildren(m2t, handle);
m2t.axesContainers{end} = addChildren(m2t.axesContainers{end}, childrenEnvs);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if m2t.axesContainers{end}.stackedBarsPresent ...
&& m2t.axesContainers{end}.nonbarPlotsPresent
userWarning(m2t, ['Pgfplots can''t deal with stacked bar plots', ...
' and non-bar plots in one axis environment.', ...
' The LaTeX file will probably not compile.']);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% The rest of this is handling axes options.
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Set view for 3D plots.
if m2t.currentAxesContain3dData
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'view', sprintf(['{', m2t.ff, '}{', m2t.ff, '}'], get(handle, 'View')));
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% the following is general MATLAB behavior
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'scale only axis', []);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Get other axis options (ticks, axis color, label,...).
% This is set here such that the axis orientation indicator in m2t is set
% before -- if ~isVisible(handle) -- the handle's children are called.
m2t.axesContainers{end}.options = merge(m2t.axesContainers{end}.options, ...
getAxisOptions(m2t, handle, 'x') ...
);
m2t.axesContainers{end}.options = merge(m2t.axesContainers{end}.options, ...
getAxisOptions(m2t, handle, 'y') ...
);
%[m2t, hasXGrid] = getAxisOptions(m2t, handle, 'x');
%[m2t, hasYGrid] = getAxisOptions(m2t, handle, 'y');
if m2t.currentAxesContain3dData
%[m2t, hasZGrid] = getAxisOptions(m2t, handle, 'z');
m2t.axesContainers{end}.options = ...
merge(m2t.axesContainers{end}.options, ...
getAxisOptions(m2t, handle, 'z') ...
);
end
hasXGrid = false;
hasYGrid = false;
hasZGrid = false;
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ~isVisible(handle)
% Setting hide{x,y} axis also hides the axis labels in Pgfplots whereas
% in MATLAB, they may still be visible. Well.
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'hide axis', []);
end
%if ~isVisible(handle)
% % An invisible axes container *can* have visible children, so don't
% % immediately bail out here.
% children = get(handle, 'Children');
% for child = children(:)'
% if isVisible(child)
% % If the axes contain something that's visible, add an invisible
% % axes pair.
% m2t.axesContainers{end}.name = 'axis';
% m2t.axesContainers{end}.options = {m2t.axesContainers{end}.options{:}, ...
% 'hide x axis', 'hide y axis'};
% m2t.axesContainers{end}.comment = getTag(handle);
% break;
% end
% end
% % recurse into the children of this environment
% [m2t, childrenEnvs] = handleAllChildren(m2t, handle);
% m2t.axesContainers{end} = addChildren(m2t.axesContainers{end}, childrenEnvs);
% return
%end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% This used to discriminate between semilog{x,y}axis, loglog, and axis.
% Now, the log-scale is handled by the {x,y,z}mode argument, so just go for
% axis.
m2t.axesContainers{end}.name = 'axis';
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% set alignment options
if ~isempty(alignmentOptions.opts)
m2t.axesContainers{end}.options = cat(1,m2t.axesContainers{end}.options,...
alignmentOptions.opts);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% background color
backgroundColor = get(handle, 'Color');
if ~strcmp(backgroundColor, 'none')
[m2t, col] = getColor(m2t, handle, backgroundColor, 'patch');
if ~strcmp(col, 'white')
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'axis background/.style', sprintf('{fill=%s}', col));
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% title
title = get(get(handle, 'Title'), 'String');
if ~isempty(title)
titleInterpreter = get(get(handle, 'Title'), 'Interpreter');
title = prettyPrint(m2t, title, titleInterpreter);
titleStyle = getFontStyle(m2t, get(handle,'Title'));
if length(title) > 1
titleStyle = addToOptions(titleStyle, 'align', 'center');
end
if ~isempty(titleStyle)
m2t.axesContainers{end}.options = addToOptions(...
m2t.axesContainers{end}.options, 'title style', ...
sprintf('{%s}', prettyprintOpts(m2t, titleStyle, ',')));
end
title = join(m2t, title, '\\[1ex]');
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'title', sprintf('{%s}', title));
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% axes locations
boxOn = strcmp(get(handle, 'box'), 'on');
xloc = get(handle, 'XAxisLocation');
if boxOn
if strcmp(xloc, 'bottom')
% default; nothing added
elseif strcmp(xloc, 'top')
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'axis x line*', 'top');
else
error('matlab2tikz:drawAxes', ...
'Illegal axis location ''%s''.', xloc);
end
else % box off
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'axis x line*', xloc);
end
yloc = get(handle, 'YAxisLocation');
if boxOn
if strcmp(yloc, 'left')
% default; nothing added
elseif strcmp(yloc, 'right')
m2t.axesContainers{end}.options = ...
addToOptions(m2t.axesContainers{end}.options, ...
'axis y line*', 'right');
else
error('matlab2tikz:drawAxes', ...
'Illegal axis location ''%s''.', yloc);
end
else % box off
m2t.axesContainers{end}.options = ...