Are Arithmetic Operations on a Cell Array of sym Objects Documented Behavior?

I inadvertently stumbled across this behavior:
syms z
H(z) = 1/(z+1) - 1/(z+2)
H(z) = 
c = children(H(z))
c = 1×2 cell array
{[1/(z + 1)]} {[-1/(z + 2)]}
whos c
Name Size Bytes Class Attributes c 1x2 224 cell
c is a cell array of sym objects. At this point, I thought that in order to operate on the elements of c I'd have to first extract them from c. However, that's not the case here
c*z % multiplies each element of c by z
ans = 
Note that the result is returned as an array of sym, not a cell array of sym
whos ans
Name Size Bytes Class Attributes ans 1x2 8 sym
So this works, which is actually what I wanted to do
sum(c*z)
ans = 
Elementwise operation works as well
c + [z 2*z] % element wise addition
ans = 
c .* [z 2*z] % elemetwise multiplication
ans = 
Is this very useful behavior documented anywhere (I couldn't find it)? I'd like to know what operations are supported on cellsym (is that the right term) arrays.
These results also suggest a way to operate on numeric cell arrays without using cellfun.
c = {1,2}
c = 1×2 cell array
{[1]} {[2]}
c = mat2cell(double(c*sym(2)),1,ones(1,numel(c)))
c = 1×2 cell array
{[2]} {[4]}

3 Comments

c = {1,2};
c = 1×2 cell array
{[1]} {[2]}
double(c*sym(2))
ans = 1×2
2 4
is just converting the symbolic representation to an array -- I don't see much point; one can do
num2cell(2*[c{:}])
far more efficiently.
The rest with symbolic just seems to be to be a result of how symbolics would have to work to be useful. I don't have the TB so never played with it much; not terribly surprising it uses cell arrays as storage mechanism.
Maybe I don't follow what seems surprising in not having the toolbox, though...
I was just surprised that this doesn't throw an error
syms z
c = {z , z};
c + z^2
ans = 
when this does
c = {1 ,2};
c + 2
Operator '+' is not supported for operands of type 'cell'.
So that error message isn't actually correct, as there are cases where operator + is supported when an operand is of type cell as in the first case, for which I can't find any supporting documentation.
syms z
c = {z , z};
c + z^2
ans = 
class(ans)
ans = 'sym'
That's easy -- the cell is promoted to 'sym' before the addition. That's basic rule that nothing is declared and of an immutable class on assignment and the dynamic allocation in MATLAB. It's the Symbolic TB taking over with the overloaded operators that makes it transparent (mostly).

Sign in to comment.

Answers (0)

Products

Release

R2022b

Asked:

on 23 Oct 2022

Commented:

dpb
on 24 Oct 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!