[4] | 1 | function sp=plus(sp1,sp2) |
---|
| 2 | % sympoly/plus: Adds two sympoly objects, or adds a numeric var to a sympoly |
---|
| 3 | % usage: sp = sp1 + sp2; |
---|
| 4 | % |
---|
| 5 | % arguments: |
---|
| 6 | % sp,sp1,sp2 - sympoly objects or scalars |
---|
| 7 | |
---|
| 8 | % are we adding scalar objects or arrays? |
---|
| 9 | s1 = numel(sp1); |
---|
| 10 | s2 = numel(sp2); |
---|
| 11 | |
---|
| 12 | % make sure both sp1 and sp2 are sympoly objects |
---|
| 13 | if ~isa(sp1,'sympoly') |
---|
| 14 | sp1 = sympoly(sp1); |
---|
| 15 | end |
---|
| 16 | if ~isa(sp2,'sympoly') |
---|
| 17 | sp2 = sympoly(sp2); |
---|
| 18 | end |
---|
| 19 | |
---|
| 20 | if (s1>1) && (s2 == 1) |
---|
| 21 | % s1 is an array or vector, s2 is a scalar |
---|
| 22 | sp = sp1; |
---|
| 23 | for i = 1:s1 |
---|
| 24 | sp(i) = sp(i) + sp2; |
---|
| 25 | end |
---|
| 26 | |
---|
| 27 | elseif (s1 == 1) && (s2 > 1) |
---|
| 28 | % s1 is an array or vector, s2 is a scalar |
---|
| 29 | sp = sp2; |
---|
| 30 | for i = 1:s2 |
---|
| 31 | sp(i) = sp1 + sp(i); |
---|
| 32 | end |
---|
| 33 | |
---|
| 34 | elseif (s1 > 1) && (s2 > 1) |
---|
| 35 | % s1 and s2 are both arrays or vectors |
---|
| 36 | |
---|
| 37 | % verify they are compatible in size |
---|
| 38 | if any(size(sp1)~=size(sp2)) |
---|
| 39 | error 'Addition attempted on sympoly arrays of incompatible size' |
---|
| 40 | end |
---|
| 41 | |
---|
| 42 | % add elementwise |
---|
| 43 | sp = sp1; |
---|
| 44 | for i = 1:s1 |
---|
| 45 | sp(i) = sp(i) + sp2(i); |
---|
| 46 | end |
---|
| 47 | |
---|
| 48 | elseif (s1==0) || (s2==0) |
---|
| 49 | % one must have been empty |
---|
| 50 | error 'Cannot add an empty array to a sympoly.' |
---|
| 51 | |
---|
| 52 | else |
---|
| 53 | % both must be scalars, and both were forced to be sympolys |
---|
| 54 | |
---|
| 55 | % make sure they have compatible variable sets |
---|
| 56 | [sp1,sp2] = equalize_vars(sp1,sp2); |
---|
| 57 | |
---|
| 58 | % the addition just requires appending the arrays, then a |
---|
| 59 | % call to consolidator |
---|
| 60 | sp = sp1; |
---|
| 61 | sp.Exponent = [sp.Exponent;sp2.Exponent]; |
---|
| 62 | sp.Coefficient = [sp.Coefficient;sp2.Coefficient]; |
---|
| 63 | |
---|
| 64 | % clean up the poly |
---|
| 65 | sp = clean_sympoly(sp); |
---|
| 66 | |
---|
| 67 | end |
---|
| 68 | |
---|