Overloading math operations on cell arrays

2 次查看(过去 30 天)
It is easy to add two cell arrays together with a function that indexes into each array, and adds. Of course the arrays must be compatible. The advantage is that they don't have to be uniform. For example, one might combine scalars and a matrix, like {1,[2,3;4,5],6}, and two cell arrays with compatible entries have an obvious sum.
Is it possible to define an overloaded addition (etc) to add any two such compatible cell arrays?
Some people would say it is unnecessary, but it would shorten my code, and improve readability. I don't want to define a class, but just add cell arrays without fuss. Of course, I can do it through function calls, but the result is longer and less readable. This may be generally useful in other applications with nonhomogeneous arrays.
  1 个评论
James Tursa
James Tursa 2022-6-8
I suppose you might be able to find the correct subfolder location to put a plus.m file that acts on cell arrays, but this practice is not advised because now every program will see it and maybe you will break some existing code that depends on this functionality not working in this way.

请先登录,再进行评论。

回答(2 个)

the cyclist
the cyclist 2022-6-8
Your question is not perfectly clear to me, but it seems that cellfun might do what you want:
A = {1,[2,3;4,5],6};
B = {2,[3,4;5,6],7};
C = cellfun(@(x,y)(x+y),A,B,'UniformOutput',false)
C = 1×3 cell array
{[3]} {2×2 double} {[13]}

Matt J
Matt J 2022-6-8
编辑:Matt J 2022-6-8
I don't want to define a class, but just add cell arrays without fuss.
What's the big deal with defining a class? See attached.
A=numericCell(num2cell(eye(3))),
A =
{[1]} {[0]} {[0]} {[0]} {[1]} {[0]} {[0]} {[0]} {[1]}
B=A+2
B =
{[3]} {[2]} {[2]} {[2]} {[3]} {[2]} {[2]} {[2]} {[3]}
C=A+2*B
C =
{[7]} {[4]} {[4]} {[4]} {[7]} {[4]} {[4]} {[4]} {[7]}

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by