Discrete.m 53.2 KB
Newer Older
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
classdef  (InferiorClasses = {?quantity.Symbolic, ?quantity.Operator}) Discrete < handle & matlab.mixin.Copyable
	properties (SetAccess = protected)
		% Discrete evaluation of the continuous quantity
		valueDiscrete double;
		
		% Grid for the evaluation of the continuous quantity. For the
		% example with the function f(x,t), the grid would be
		%   {[<spatial domain>], [<temporal domain>]}
		% whereas <spatial domain> is the discret description of the
		% spatial domain and <temporal domain> the discrete description of
		% the temporal domain.
		grid; % in set.grid it is ensured that, grid is a (1,:)-cell-array
		
		% Name of the domains that generate the grid.
		gridName {mustBe.unique};
		
		% In this cell, already computed derivatives can be stored to avoid
		% multiple computations of the same derivative.
		derivatives cell = {};
	end
	
	properties (Hidden, Access = protected, Dependent)
		doNotCopy;
	end
	
	properties
		% ID of the figure handle in which the handle is plotted
		figureID double = 1;
		
		% TODO@ff vermutlich ist es schöner einen converter auf dieses
		% Objekt zu schreiben, als es hier als Eigenschaft dran zu hängen.
		exportData export.Data;
		
		% Name of this object
		name char;
	end
	
	methods
		%--------------------
		% --- Constructor ---
		%--------------------
		function obj = Discrete(valueOriginal, varargin)
			% The constructor requires valueOriginal to be
			% 1) a cell-array of double arrays with
			%	size(valueOriginal) == size(obj) and
			%	size(valueOriginal{it}) == gridSize
			% OR
			% 2) adouble-array with
			%	size(valueOriginal) == [gridSize, size(quantity)] 
			% Furthermore, 'gridName' must be part of the name-value-pairs
			% in varargin. Additional parameters can be specified using
			% name-value-pair-syntax in varargin.
			
			% to allow the initialization as object array, the constructor
			% must be allowed to be called without arguments
			if nargin > 0
				
				%% allow initialization of empty objects:
				valueOriginalSize = size(valueOriginal);
				S = num2cell(valueOriginalSize);
				if any(valueOriginalSize == 0)
					obj = quantity.Discrete.empty(S{:});
					return;
				end
				
				%% input parser
				myParser = misc.Parser();
				myParser.addParameter('gridName', []);
				myParser.addParameter('grid', []);
				myParser.addParameter('name', string());
				myParser.addParameter('figureID', 1);
				myParser.parse(varargin{:});
				assert(all(~contains(myParser.UsingDefaults, 'gridName')), ...
					'gridName is a mandatory input for quantity');
				
				if iscell(myParser.Results.gridName)
					myGridName = myParser.Results.gridName;
				else
					myGridName = {myParser.Results.gridName};
				end
				
				%% get the sizes of obj and grid
				if iscell(valueOriginal)
					if isempty(valueOriginal{1})
						% if valueOriginal is a cell-array with empty
						% cells, then grid must be specified as an input
						% parameter. This case is important for
						% constructing Symbolic or Function quantities
						% without discrete values.
						assert(all(~contains(myParser.UsingDefaults, 'grid')), ...
							['grid is a mandatory input for quantity, ', ...
							'if no discrete values are specified']);
						if ~iscell(myParser.Results.grid)
							gridSize = numel(myParser.Results.grid);
						else
							gridSize = cellfun(@(v) numel(v), myParser.Results.grid);
						end
					else
						gridSize = size(valueOriginal{1});
					end
					objSize = size(valueOriginal);
				elseif isnumeric(valueOriginal)
					gridSize = valueOriginalSize(1 : numel(myGridName));
					objSize = [valueOriginalSize(numel(myGridName)+1 : end), 1, 1];
				end
				
				%% get grid and check size
				if any(contains(myParser.UsingDefaults, 'grid'))
					myGrid = quantity.Discrete.defaultGrid(gridSize);
				else
					myGrid = myParser.Results.grid;
				end
				if ~iscell(myGrid)
					myGrid = {myGrid};
				end
				if isempty(myGridName) || isempty(myGrid)
					if ~(isempty(myGridName) && isempty(myGrid))
						error(['If one of grid and gridNames is empty, ', ...
							'then both must be empty.']);
					end
				else
					assert(isequal(size(myGrid), size(myGridName)), ...
						'number of grids and gridNames must be equal');
					myGridSize = cellfun(@(v) numel(v), myGrid);
					assert(isequal(gridSize(gridSize>1), myGridSize(myGridSize>1)), ...
						'grids do not fit to valueOriginal');
				end
				
				%% set valueDiscrete
				if ~iscell(valueOriginal)
					valueOriginal = quantity.Discrete.value2cell(valueOriginal, gridSize, objSize);
				end
				for k = 1:prod(objSize)
					if numel(myGrid) == 1
						obj(k).valueDiscrete = valueOriginal{k}(:);
					else
						obj(k).valueDiscrete = valueOriginal{k};
					end
				end
				
				%% set further properties
				[obj.grid] = deal(myGrid);
				[obj.gridName] = deal(myGridName);
				[obj.name] = deal(myParser.Results.name);
				[obj.figureID] = deal(myParser.Results.figureID);
				
				%% reshape object from vector to matrix
				obj = reshape(obj, objSize);
			end
		end% Discrete() constructor

		%---------------------------
		% --- getter and setters ---
		%---------------------------
		function doNotCopy = get.doNotCopy(obj)
			doNotCopy = obj.doNotCopyPropertiesName();
		end
		function exportData = get.exportData(obj)
			if isempty(obj.exportData)
				if obj.nargin == 1
					obj.exportData = export.dd(...
						'M', [obj.grid{:}, obj.valueDiscrete], ...
						'header', {'t', 'y1', 'y2'}, ...
						'filename', 'plot', ...
						'basepath', '.' ... % TODO changed basepath to '.'
						);
				elseif obj.nargin == 2
					obj.exportData  = export.ddd();
				else
					error('Not yet implemented')
				end
				exportData = obj.exportData;
			end
		end
		function set.gridName(obj, name)
			if ~iscell(name)
				name = {name};
			end
			obj.gridName = name;
		end
		
		function set.grid(obj, grid)
			if ~iscell(grid)
				grid = {grid};
			end
			
			isV = cellfun(@(v) isvector(v), grid);
			assert(all(isV(:)), 'Please use vectors for the grid entries!');
			
			[obj.grid] = deal(grid);
		end
		
		function valueDiscrete = get.valueDiscrete(obj)
			if isempty(obj.valueDiscrete)
				obj.valueDiscrete = obj.on(obj.grid);
			end
			valueDiscrete = obj.valueDiscrete;
		end
		
		%--------------
		% --- casts ---
		%--------------
		function d = double(obj)
			d = obj.on();
		end
	end
	
	methods (Access = public)
				
		function value = on(obj, myGrid, myGridName)
			% TODO es sieht so aus als würde die Interpolation bei
			% konstanten werten ziemlichen Quatsch machen!
			%	Da muss man nochmal ordentlich drauf schauen!
			if isempty(obj)
				value = zeros(size(obj));
			else
				if nargin == 1
					myGrid = obj(1).grid;
				elseif nargin >= 2 && ~iscell(myGrid)
					myGrid = {myGrid};
				end
				gridPermuteIdx = 1:obj(1).nargin;
				if nargin == 3
					if ~iscell(myGridName)
						myGridName = {myGridName};
					end
					assert(numel(myGrid) == numel(myGridName), ...
						['If on() is called by using gridNames as third input', ...
						', then the cell-array of grid and gridName must have ', ...
						'equal number of elements.']);
					assert(numel(myGridName) == obj(1).nargin, ...
						'All (or none) gridName must be specified');
					gridPermuteIdx = cellfun(@(v) obj(1).gridIndex(v), myGridName);
					myGrid = myGrid(gridPermuteIdx);
				end
				
				value = obj.obj2value();
				
				if nargin >= 2 && (prod(obj(1).gridSize) > 1)
					indexGrid = arrayfun(@(s)linspace(1,s,s), size(obj), 'UniformOutput', false);
					tempInterpolant = numeric.interpolant(...
						[obj(1).grid, indexGrid{:}], value);
					value = tempInterpolant.evaluate(myGrid{:}, indexGrid{:});
				end
				value = permute(reshape(value, [cellfun(@(v) numel(v), myGrid), size(obj)]), ...
					[gridPermuteIdx, numel(gridPermuteIdx)+(1:ndims(obj))]);
			end
		end
		
		function solution = solveAlgebraic(obj, rhs, gridName, objLimit)
			%% this method solves
			%	obj(gridName) == rhs
			% for the variable specified by gridName.
			% rhs must be of apropriate size and gridName must
			% be an gridName of obj. If the result is constant (i.e., if
			% obj only depends on variable, then a double array is
			% returned. Else the solution is of the type as obj.
			% Yet, this is only implemented for obj with one variable
			% (grid) (see quantity.invert-method).
			% The input objLimit specifies minimum and maximum of the
			% values of obj, between which the solution should be searched.
			assert(numel(obj(1).gridName) == 1);
			assert(isequal(size(obj), [1, 1]));
			
			if ~isequal(size(rhs), size(obj))
				error('rhs has not the same size as quantity');
			end
			if ~iscell(gridName)
				gridName = {gridName};
			end
			if numel(gridName) ~= 1
				error('this function can only solve for one variable');
			end
			if isempty(strcmp(obj(1).gridName, gridName{1}))
				error('quantity does not depend on variable');
			end
			
			if nargin == 4
				assert(numel(objLimit)==2, 'a lower and upper limit must be specified (or neither)');
				objValueTemp = obj.on();
				gridSelector = (objValueTemp >= objLimit(1)) & (objValueTemp <= objLimit(2));
				gridSelector([find(gridSelector, 1, 'first')-1, find(gridSelector, 1, 'last')+1]) = 1;
				limitedGrid = obj(1).grid{1}(gridSelector);
				objCopy = obj.copy();
				objCopy.changeGrid({limitedGrid}, gridName);
				objInverseTemp = objCopy.invert(gridName);
			else
				objInverseTemp = obj.invert(gridName);
			end
			
			solution = objInverseTemp.on(rhs);

% 			solution = zeros(numel(obj), 1);
% 			for it = 1 : numel(obj)
% 				objInverseTemp = obj(it).invert(gridName);
% 				solution(it) = objInverseTemp.on(rhs(it));				
% 			end
% 			solution = reshape(solution, size(obj));
		end
		
		function inverse = invert(obj, gridName)
			% inverse solves the function representet by the quantity for
			% its variable, for instance, if obj represents y = f(x), then
			% invert returns an object containing x = f^-1(y).
			% Yet, this is only implemented for obj with one variable
			% (grid).
			assert(numel(obj(1).gridName) == 1);
			assert(isequal(size(obj), [1, 1]));
			inverse = quantity.Discrete(repmat(obj(1).grid{obj.gridIndex(gridName)}(:), [1, size(obj)]), ...
				'size', size(obj), 'grid', obj.on(), 'gridName', {[obj(1).name]}, ...
				'name', gridName);
			
		end
		
		function solution = solveDVariableEqualQuantity(obj, varargin)
			%% solves the first order ODE
			%	dvar / ds = obj(var(s))
			%	var(s=0) = ic
			% for var(s, ic). Herein, var is the (only) continuous variale
			% obj.variable. The initial condition of the IVP is a variable
			% of the result var(s, ic).
			assert(numel(obj(1).gridName) == 1, ...
				'this method is only implemented for quanitities with one gridName');
			
			myParser = misc.Parser();
			myParser.addParameter('initialValueGrid', obj(1).grid{1});
			myParser.addParameter('variableGrid', obj(1).grid{1});
			myParser.addParameter('newGridName', 's');
			myParser.addParameter('RelTol', 1e-6);
			myParser.addParameter('AbsTol', 1e-6);
			myParser.parse(varargin{:});
			
			variableGrid = myParser.Results.variableGrid;
			myGridSize = [numel(variableGrid), ... 
				numel(myParser.Results.initialValueGrid)];
			
			% the time (s) vector has to start at 0, to ensure the IC.
			% If variableGrid does not start with 0, it is separated in
			% negative and positive parts and later combined again.
			positiveVariableGrid = [0, variableGrid(variableGrid > 0)];
			negativeVariableGrid = [0, flip(variableGrid(variableGrid < 0))];
			
			% solve ode for every entry in obj and for every initial value
			options = odeset('RelTol', myParser.Results.RelTol, 'AbsTol', myParser.Results.AbsTol);
			odeSolution = zeros([myGridSize, numel(obj)]);
			for it = 1:numel(obj)
				for icIdx = 1:numel(myParser.Results.initialValueGrid)
					resultGridPositive = [];
					odeSolutionPositive = [];
					resultGridNegative = [];
					odeSolutionNegative = [];
					if numel(positiveVariableGrid) > 1
						[resultGridPositive, odeSolutionPositive] = ...
							ode45(@(y, z) obj(it).on(z), ...
								positiveVariableGrid, ...
								myParser.Results.initialValueGrid(icIdx), options);
					end
					if numel(negativeVariableGrid) >1
						[resultGridNegative, odeSolutionNegative] = ...
							ode45(@(y, z) obj(it).on(z), ...
								negativeVariableGrid, ...
								myParser.Results.initialValueGrid(icIdx), options);
					end
					if any(variableGrid == 0)
						resultGrid = [flip(resultGridNegative(2:end)); 0 ; resultGridPositive(2:end)];
						odeSolution(:, icIdx, it) = [flip(odeSolutionNegative(2:end)); ...
							myParser.Results.initialValueGrid(icIdx); odeSolutionPositive(2:end)];
					else
						resultGrid = [flip(resultGridNegative(2:end)); resultGridPositive(2:end)];
						odeSolution(:, icIdx, it) = [flip(odeSolutionNegative(2:end)); ...
							odeSolutionPositive(2:end)];
					end
					assert(isequal(resultGrid(:), variableGrid(:)));
				end
			end
			
			% return result as quantity-object
			solution = quantity.Discrete(...
				reshape(odeSolution, [myGridSize, size(obj)]), ...
				'gridName', {myParser.Results.newGridName, 'ic'}, 'grid', ...
				{variableGrid, myParser.Results.initialValueGrid}, ...
				'size', size(obj), 'name', ['solve(', obj(1).name, ')']);
		end
		
		function solution = subs(obj, gridName2Replace, values)
			if nargin == 1 || isempty(gridName2Replace)
				% if gridName2Replace is empty, then nothing must be done.
				solution = obj;
			else
				% input checks
				assert(nargin == 3, ['Wrong number of input arguments. ', ...
					'gridName2Replace and values must be cell-arrays!']);
				if ~iscell(gridName2Replace)
					gridName2Replace = {gridName2Replace};
				end
				if ~iscell(values)
					values = {values};
					assert(numel(values) == numel(gridName2Replace), ...
						'gridName2Replace and values must be of same size');
				end
				
				% here substitution starts: 
				% The first (gridName2Replace{1}, values{1})-pair is 
				% replaced. If there are more cell-elements in those inputs
				% then subs() is called again for the remaining pairs
				% (gridName2Replace{2:end}, values{2:end}).
				if ischar(values{1})
					% if values{1} is a char-array, then the gridName is
					% replaced
					if any(strcmp(values{1}, gridName2Replace(2:end)))
						% in the case if a quantity f(z, zeta) should be
						% substituted like subs(f, {z, zeta}, {zeta, z})
						% this would cause an error, since after the first
						% substituion subs(f, z, zeta) the result would
						% be f(zeta, zeta) -> the 2nd subs(f, zeta, z) will
						% result in f(z, z) and not in f(zeta, z) as
						% intended. This is solved, by an additonal
						% substitution:
						values{end+1} = values{1};
						gridName2Replace{end+1} = [gridName2Replace{1}, 'backUp'];
						values{1} = [gridName2Replace{1}, 'backUp'];
					end
					if any(strcmp(values{1}, obj(1).gridName))
						% if for a quantity f(z, zeta) this method is
						% called with subs(f, zeta, z), then
						% g(z) = f(z, z) results, hence the dimensions z
						% and zeta are merged.
						gridIndices = [obj(1).gridIndex(gridName2Replace{1}), ...
							obj(1).gridIndex(values{1})];
						newGridForOn = obj(1).grid;
						if numel(obj(1).grid{gridIndices(1)}) > numel(obj(1).grid{gridIndices(2)})
							newGridForOn{gridIndices(2)} = newGridForOn{gridIndices(1)};
						else
							newGridForOn{gridIndices(1)} = newGridForOn{gridIndices(2)};
						end
						newValue = misc.diagNd(obj.on(newGridForOn), gridIndices);
						newGrid = {newGridForOn{gridIndices(1)}, ...
							newGridForOn{any(1:1:numel(newGridForOn)) ~= gridIndices(1) ...
							 & any(1:1:numel(newGridForOn)) ~= gridIndices(2)}};
						newGridName = {values{1}, ...
							obj(1).gridName{any(1:1:numel(obj(1).gridName)) ~= gridIndices(1) ...
							 & any(1:1:numel(obj(1).gridName)) ~= gridIndices(2)}};
						
					else
						% this is the default case. just grid name is
						% changed.
						newGrid = obj(1).grid;
						newGridName = obj(1).gridName;
						newGridName{obj(1).gridIndex(gridName2Replace{1})} ...
							= values{1};
						newValue = obj.on();
					end
					
				elseif isnumeric(values{1}) && numel(values{1}) == 1
					% if values{1} is a scalar, then obj is evaluated and
					% the resulting quantity loses that spatial grid and
					% gridName
					newGridName = obj(1).gridName;
					newGridName = newGridName(~strcmp(newGridName, gridName2Replace{1}));
					% newGrid is the similar to the original grid, but the
					% grid of gridName2Replace is removed.
					newGrid = obj(1).grid;
					newGrid = newGrid((1:1:numel(newGrid)) ~= obj.gridIndex(gridName2Replace{1}));
					newGridSize = cellfun(@(v) numel(v), newGrid);
					% newGridForOn is the similar to the original grid, but the
					% grid of gridName2Replace is set to values{1} for evaluation of obj.on().
					newGridForOn = obj(1).grid;
					newGridForOn{obj.gridIndex(gridName2Replace{1})} = values{1};
					newValue = reshape(obj.on(newGridForOn), [newGridSize, size(obj)]);
					
				elseif isnumeric(values{1}) && numel(values{1}) > 1
					% if values{1} is a double vector, then the grid is
					% replaced.
					newGrid = obj(1).grid;
					newGrid{obj.gridIndex(gridName2Replace{1})} = values{1};
					newGridName = obj(1).gridName;
					newValue = obj.on(newGrid);
				else
					error('value must specify a gridName or a gridPoint');
				end
				if isempty(newGridName)
					solution = newValue;
				else
					solution = quantity.Discrete(newValue, ...
						'grid', newGrid, 'gridName', newGridName, ...
						'name', obj(1).name);
				end
				if numel(gridName2Replace) > 1
					solution = solution.subs(gridName2Replace(2:end), values(2:end));
				end
			end
			
		end
% 		function solution = subs(obj, gridName, values)
% 			% This function substitutes the variables specified with
% 			% gradName with values. It can be used to rename grids or to
% 			% evaluate (maybe just some) grids.
% 			% GridName is cell-array of char-arrays
% 			% chosen from obj.gridName-property. Values is a cell-array of
% 			% the size of gridName. Each cell can contain arrays themself,
% 			% but those arrays must be of same size. Values can be
% 			% char-arrays standing for new gridNames or or numerics.
% 			% In contrast to on() or at(), only some, but not necessarily
% 			% all variables are evaluated.
% 			if ~iscell(gridName)
% 				gridName = {gridName};
% 			end
% 			if ~iscell(values)
% 				values = {values};
% 			end
% 			isNumericValue = cellfun(@isnumeric, values);
% 			if any((cellfun(@(v) numel(v(:)), values)>1) & isNumericValue)
% 				error('only implemented for one value per grid');
% 			end
% 			numericValues = values(isNumericValue);
% 			if numel(obj(1).gridName) == numel(numericValues)
% 				% if all grids are evaluated, solution is a double array.
% 				solution = reshape(obj.on(numericValues), size(obj));
% 			else
% 				% evaluate numeric values
% 				subsGrid = obj(1).grid;
% 				selectRemainingGrid = false(1, numel(obj(1).grid));
% 				for currentGridName = gridName(isNumericValue)
% 					selectGrid = strcmp(obj(1).gridName, currentGridName);
% 					subsGrid{selectGrid} = values{strcmp(gridName, currentGridName)};
% 					selectRemainingGrid = selectRemainingGrid | selectGrid;
% 				end
% 				newGrid = obj(1).grid(~selectRemainingGrid);
% 				newGridName = obj(1).gridName(~selectRemainingGrid);
% 				for it = 1 : numel(values)
% 					if ~isNumericValue(it) && ~isempty(obj(1).gridName(~selectRemainingGrid))
% 						newGridName{strcmp(obj(1).gridName(~selectRemainingGrid), gridName{it})} ...
% 							= values{it};
% 					end
% 				end
% 				% before creating a new quantity, it is checked that
% 				% newGridName is unique. If there are non-unique
% 				% gridNames, multiple ones are removed and the finest grid
% 				% from newGrid is taken.
% 				[uniqueGridName] = unique(newGridName);
% 				for kt = 1 : numel(uniqueGridName)
% 					% select finest grid
% 					sameGridSelector = strcmp(newGridName, uniqueGridName{kt});
% 					gridCandidates = subsGrid(sameGridSelector);
% 					gridCandidate = gridCandidates{1};
% 					for asdf = 2 : numel(gridCandidates)
% 						if numel(gridCandidate) < numel(gridCandidates{asdf})
% 							gridCandidate = gridCandidates{asdf};
% 						end
% 						subsGrid(sameGridSelector) = {gridCandidate};
% 					end
% 					[newGrid{strcmp(newGridName, uniqueGridName{kt})}] = deal(gridCandidate);
% 				end
% 				
% 				newValue = reshape(obj.on(subsGrid), [cellfun(@numel, newGrid), size(obj)]);
% 				k = 1;
% 				while numel(newGridName) > numel(uniqueGridName)
% 					% elemenate non-diagonal elements
% 					sameGridSelector = strcmp(newGridName, uniqueGridName{k});
% 					if sum(sameGridSelector) > 1
% 						sameGridIndex = 1:numel(newGridName);
% 						sameGridIndex = sameGridIndex(sameGridSelector);
% 						newValue = misc.diagNd(newValue, sameGridIndex);
% 						newGrid = [newGrid(sameGridIndex(1)), ...
% 							newGrid(all((1:numel(newGrid) ~= sameGridIndex(:) )))];
% 						newGridName = {newGridName{sameGridIndex(1)}, ...
% 							newGridName{all((1:numel(newGridName) ~= sameGridIndex(:) ))}};
% 					end
% 					k = k+1;
% 				end
% 				solution = quantity.Discrete(newValue, 'size', size(obj), ...
% 					'gridName', newGridName, 'grid', newGrid, 'name', obj(1).name);
% 				
% 			end
% 		end
		
		
		% at evaluates the given function at the given grid points.
		%   value = at(obj, grid, index) returns the evaluated
		%   function as an array with the dimensions:
		%       dim(value) = [length(z), size(obj)].
		%   For example, the quantity describes an array valued function
		%       f(z) = [f1(z), f2(z), f3(z); ...
		%               f4(z), f5(z), f6(z)],
		%   i.e., it has the dimensions (2, 3) and a vector Z for the N =
		%   11 discretization points Z = [0; 0.1; ...; 1]. By calling the
		%   evaluate function for this quantity an array of dimensions (11,
		%   2, 3) will be returned.
		function value = at(obj, point)
			value = shiftdim(obj.on(point), 1);
		end
		
		function value = atIndex(obj, varargin)
			% ATINDEX TODO@ff ausführliche doku schreiben, da die Funktion
			% sich ungewöhnlich verhält, wenn man sie ohne idx argument
			% aufruft.
			if nargin == 1
				value = 1:obj.gridSize;
				if isempty(value)
					value = 0;
				end
			else
				if ~iscell(varargin)
					varargin = {varargin};
				end
				value = cellfun(@(v) v(varargin{:}), {obj.valueDiscrete});
				value = reshape(value, size(obj));
			end
		end
		
		
		function n = nargin(obj)
			% FIXME: check if all funtions in this object have the same
			% number of input values.
			n = numel(obj(1).gridName);
		end
		
		function d = gridDiff(obj)
			
			% #FIXME:
			%   1) test for multidimensional grids
			%   2) check that the grid is equally spaced
			
			d = diff(obj(1).grid{:});
			d = d(1);
		end
		
		function s = gridSize(obj)
			% GRIDSIZE returns the size of all grid entries.
			if isempty(obj(1).grid)
				s = [];
			else
				s = cellfun('length', obj(1).grid);
			end
		end
		
		function matGrid = ndgrid(obj, grid)
			% ndgrid calles ndgrid for the default grid, if no other grid
			% is specified. Empty grid as input returns empty cell as result.
			if nargin == 1
				grid = obj.grid;
			end
			if isempty(grid)
				matGrid = {};
			else
				[matGrid{1:obj.nargin}] = ndgrid(grid{:});
			end
		end
		
		function h = plot(obj, varargin)
			
			p = misc.Parser();
			p.addParameter('fig', []);
			p.addParameter('dock', false);
			p.parse(varargin{:});
			%misc.struct2ws(p.Results);
			fig = p.Results.fig;
			dock = p.Results.dock;
			for figureIdx = 1:size(obj, 3)
				if isempty(p.Results.fig)
					h = figure();
				else
				h = figure(fig + figureIdx - 1);
				end
				
				if dock
					set(h, 'WindowStyle', 'Docked');
				end
				
				assert(obj.nargin() <= 2);
				
				subplotRowIdx = 1:size(obj, 1);
				subpotColumnIdx = 1:size(obj, 2);
				
				i = 1: numel(obj(:,:,figureIdx));
				i = reshape(i, size(obj, 2), size(obj, 1))';
				
				for rowIdx = subplotRowIdx
					for columnIdx = subpotColumnIdx
						subplot(size(obj, 1), size(obj, 2), i(rowIdx, columnIdx));
						
						if obj.nargin() == 1
							
							plot(...
								obj(rowIdx, columnIdx, figureIdx).grid{1}, ...
								obj(rowIdx, columnIdx, figureIdx).valueDiscrete );
						elseif obj.nargin() == 2
							misc.isurf(obj(rowIdx, columnIdx, figureIdx).grid{1}(:), ...
								obj(rowIdx, columnIdx, figureIdx).grid{2}(:), ...
								obj(rowIdx, columnIdx, figureIdx).valueDiscrete);
							ylabel(labelHelper(2), 'Interpreter','latex');
						else
							error('number inputs not supported');
						end
						xlabel(labelHelper(1), 'Interpreter','latex');
						title(titleHelper(), 'Interpreter','latex');
						a = gca();
						a.TickLabelInterpreter = 'latex';
						
					end
				end
				
			end
		
			function myLabel = labelHelper(gridNumber)
				myLabel = ['$$', greek2tex(obj(rowIdx, columnIdx, figureIdx).gridName{gridNumber}), '$$'];
			end
			function myTitle = titleHelper()
				if ndims(obj) <= 2
					myTitle = ['$${', greek2tex(obj(rowIdx, columnIdx, figureIdx).name), ...
						'}_{', num2str(rowIdx), num2str(columnIdx), '}$$'];
				else
					myTitle = ['$${', greek2tex(obj(rowIdx, columnIdx, figureIdx).name), ...
						'}_{', num2str(rowIdx), num2str(columnIdx), num2str(figureIdx), '}$$'];
				end
			end
			function myText = greek2tex(myText)
				if ~contains(myText, '\')
					myText = strrep(myText, 'Lambda', '\Lambda');
					myText = strrep(myText, 'zeta', '\zeta');
					myText = strrep(myText, 'Gamma', '\Gamma');
					if ~contains(myText, 'zeta')
						myText = strrep(myText, 'eta', '\eta');
					end
					myText = strrep(myText, 'pi', '\pi');
					myText = strrep(myText, 'Pi', '\Pi');
				end
			end
			
		end
		
		function s = nameValuePair(obj, varargin)
			assert(numel(obj) == 1, 'nameValuePair must not be called for an array object');
			s = struct(obj);
			if ~isempty(varargin)
				s = rmfield(s, varargin{:});
			end
			s = misc.struct2namevaluepair(s);
		end
		
		function s = struct(obj)
			properties = fieldnames(obj);
			si = num2cell( size(obj) );
			s(si{:}) = struct();
			for l = 1:numel(obj)
				
				doNotCopyProperties = obj(l).doNotCopy;
				
				for k = 1:length(properties)
					if ~any(strcmp(doNotCopyProperties, properties{k}))
						s(l).(properties{k}) = obj(1).(properties{k});
					end
				end
				
			end
		end
		
		function s = obj2struct(obj)
			warning('depricated');
			s = struct(obj);
		end
		
		function obj = changeGrid(obj, gridNew, gridNameNew)
			% change the grid of the obj quantity. The order of grid and
			% gridName in the obj properties remains unchanged, only the
			% data points are exchanged.
			gridIndexNew = obj(1).gridIndex(gridNameNew);
			myGrid = cell(1, numel(obj(1).grid));
			myGridName = cell(1, numel(obj(1).grid));
			for it = 1 : numel(myGrid)
				myGrid{gridIndexNew(it)} = gridNew{it};
				myGridName{gridIndexNew(it)} = gridNameNew{it};
			end
			assert(isequal(myGridName(:), obj(1).gridName(:)), 'rearranging grids failed');
			
			for it = 1 : numel(obj)
				obj(it).valueDiscrete = obj(it).on(myGrid);
			end
			[obj.derivatives] = deal({});
			[obj.grid] = deal(myGrid);
		end
	end
	
	%% math
	methods (Access = public)
		function y = sqrt(x)
			% quadratic root for scalar and diagonal quantities
			y = quantity.Discrete(sqrt(x.on()), ...
				'size', size(x), 'grid', x(1).grid, 'gridName', x(1).gridName, ...
				'name', ['sqrt(', x(1).name, ')']);
		end
		
		
		function y = sqrtm(x)
			% quadratic root for matrices
			if isscalar(x)
				% use sqrt(), because its faster.
				y = sqrt(x);
			elseif (size(x, 1) == size(x, 2)) && ismatrix(x)
				% implementation of quadratic root pointwise in space in a
				% simple for-loop.
				xMat = x.on();
				permuteGridAndIdx = [[-1, 0] + ndims(xMat), 1:x.nargin];
				permuteBack = [(1:x.nargin)+2, [1, 2]];
				xPermuted = permute(xMat, permuteGridAndIdx);
				yUnmuted = 0*xPermuted;
				for k = 1 : prod(x(1).gridSize)
					yUnmuted(:,:,k) = sqrt(xPermuted(:,:,k));
				end
				y = quantity.Discrete(permute(yUnmuted, permuteBack), ...
					'size', size(x), 'grid', x(1).grid, 'gridName', x(1).gridName, ...
					'name', ['sqrt(', x(1).name, ')']);
			else
				error('sqrtm() is only implemented for quadratic matrices');
			end
		end
		
		function P = mpower(a, p)
			% a^p implemented by multiplication
			assert(p==floor(p) && p > 0);
			P = a;
			for k = 1:(p-1)
				P = P * a;
			end
		end
		
		function P = mtimes(a, b)
			% numeric computation of the matrix product
			
			ftr = false; % flag for the special case a == const.
			
			if isa(a, 'double')
				if numel(a) == 1
					% simple multiplication in scalar case
					P = quantity.Discrete(a * b.on(), 'size', size(b),...
						'grid', b(1).grid, 'gridName', b(1).gridName, ...
						'name', [num2str(a), '*', b(1).name]);
					return
				end
				a = quantity.Discrete(a, 'size', size(a), 'grid', {}, 'gridName', {});
			end
			
			if a.nargin() == 0
				% TODO: Whats the use of this?
				a_ = a;
				a = b';
				b = a_';
				ftr = true;
			end
			
			if isa(b, 'double')
				if numel(b) == 1
					% simple multiplication in scalar case
					P = quantity.Discrete(a.on() * b, 'size', size(a),...
						'grid', a(1).grid, 'gridName', a(1).gridName, ...
						'name', [a(1).name, '*', num2str(b)]);
					return
				end
				b = quantity.Discrete(b, 'size', size(b), 'grid', {}, 'gridName', {});
			end
			assert(size(a, 2) == size(b, 1), ['For multiplication the ', ...
				'number of columns of the left array', ...
				'must be equal to number of rows of right array!'])
			
			% misc.multArray is very efficient, but requires that the
			% multiple dimensions of the input are correctly arranged.
			[idx, permuteGrid] = computePermutationVectors(a, b);
						
			parameters = struct(a(1));
			parameters.name = [a(1).name, '*', b(1).name];
			parameters.grid = [...
				a(1).grid(idx.A.common), ...
				b(1).grid(~idx.B.common)];
			parameters.gridName = [...
				a(1).gridName(idx.A.grid), ...
				b(1).gridName(~idx.B.common)];
			
			% select finest grid from a and b
			parameters.grid = cell(1, numel(parameters.gridName));
			[gridJoined, gridNameJoined] = gridJoin(a, b);
			% gridJoin combines the grid of a and b while using the finer
			% of both.
			aGrid = cell(1, a.nargin); % for later call of a.on() with fine grid
			bGrid = cell(1, b.nargin); % for later call of b.on() with fine grid
			for it = 1 : numel(parameters.gridName)
				parameters.grid{it} = gridJoined{...
					strcmp(parameters.gridName{it}, gridNameJoined)};
				if a.gridIndex(parameters.gridName{it})
					aGrid{a.gridIndex(parameters.gridName{it})} = ...
						parameters.grid{it};
				end
				if b.gridIndex(parameters.gridName{it})
					bGrid{b.gridIndex(parameters.gridName{it})} = ...
						parameters.grid{it};
				end		
			end
			parameters = misc.struct2namevaluepair(parameters);
			
			valueA = permute(a.on(aGrid), idx.A.permute);
			valueB = permute(b.on(bGrid), idx.B.permute);
			
			C = misc.multArray(valueA, valueB, idx.A.value(end), idx.B.value(1), idx.common);
			C = permute(C, permuteGrid);
			P = quantity.Discrete(C, parameters{:});
			
			if ftr
				P = P';
			end
			
		end
		
		function y = inv(obj)
			% inv inverts the matrix obj at every point of the domain.
			assert(ismatrix(obj) && (size(obj, 1) == size(obj, 2)), ...
				'obj to be inverted must be quadratic');
			objDiscreteOriginal = obj.on();
			if isscalar(obj)
				% use ./ for scalar case
				y = quantity.Discrete(1 ./ objDiscreteOriginal, ...
					'size', size(obj), ...
					'name', ['(', obj(1).name, ')^{-1}'], ...
					'grid', obj(1).grid, 'gridName', obj(1).gridName);
			else
				% reshape and permute objDiscrete such that only on for loop is
				% needed.
				objDiscreteReshaped = permute(reshape(objDiscreteOriginal, ...
					[prod(obj(1).gridSize), size(obj)]), [2, 3, 1]);
				invDiscrete = zeros([prod(obj(1).gridSize), size(obj)]);

				parfor it = 1 : size(invDiscrete, 1)
					invDiscrete(it, :, :) = inv(objDiscreteReshaped(:, :, it));
				end

				y = quantity.Discrete(reshape(invDiscrete, size(objDiscreteOriginal)),...
					'size', size(obj), ...
					'name', ['(', obj(1).name, ')^{-1}'], ...
					'grid', obj(1).grid, 'gridName', obj(1).gridName);
			end
		end
		
		function y = exp(obj)
			% exp() is the exponential function using obj as the exponent.
			y = quantity.Discrete(exp(obj.on()), ...
				'name', ['exp(', obj(1).name, ')'], ...
				'grid', obj(1).grid, 'gridName', obj(1).gridName, ...
				'size', size(obj));
		end
		
		function y = expm(x)
			% exp() is the matrix-exponential function using obj as the exponent.
			if isscalar(x)
				% use exp(), because its faster.
				y = exp(x);
			elseif ismatrix(x)
				% implementation of expm pointwise in space in a
				% simple for-loop.
				xMat = x.on();
				permuteGridAndIdx = [[-1, 0] + ndims(xMat), 1:x.nargin];
				permuteBack = [(1:x.nargin)+2, [1, 2]];
				xPermuted = permute(xMat, permuteGridAndIdx);
				yUnmuted = 0*xPermuted;
				for k = 1 : prod(x(1).gridSize)
					yUnmuted(:,:,k) = expm(xPermuted(:,:,k));
				end
				y = quantity.Discrete(permute(yUnmuted, permuteBack), ...
					'size', size(x), 'grid', x(1).grid, 'gridName', x(1).gridName, ...
					'name', ['expm(', x(1).name, ')']);
			end
		end
		
		function x = mldivide(A, B)
			% mldivide see doc mldivide of matlab:
			% "x = A\B is the solution to the equation Ax = B. Matrices 
			% A and B must have the same number of rows."
			x = inv(A)*B;
		end
 		
		function x = mrdivide(B, A)
			% mRdivide see doc mrdivide of matlab:
			% "x = B/A solves the system of linear equations x*A = B for x.
			% The matrices A and B must contain the same number of columns"
			x = B * inv(A);
			
		end
		
		function P = matTimes(a, b)
			
			assert(size(a,2) == size(b,1));
			
			p = a(1).gridSize();
			q = p(2);
			p = p(1);
			A = a.on();
			B = b.on();
			
			% dimensions
			n = size(a, 1);
			m = size(b, 2);
			o = size(b, 1);
			
For faster browsing, not all history is shown. View entire blame