How to subtract number inside cell

1 visualización (últimos 30 días)
Ahmad Bayhaqi
Ahmad Bayhaqi el 5 de Jul. de 2021
Editada: Stephen23 el 5 de Jul. de 2021
Hi ,
For example I have 2 arrays. A and B.
A= 2x1 cell
inside A > [32,28,30,31] [27,29,30]
B 2x 1 cell
inside B > [30,64,72,85] [15,33,62]
I want to do subtract for A-B in each entry. The expected results are C: 2x 1 cell > [2,-36,-42,-54] [12,-4,-32]
How do I do this?
Thank you

Respuestas (2)

Stephen23
Stephen23 el 5 de Jul. de 2021
A = {[32,28,30,31],[27,29,30]};
B = {[30,64,72,85],[15,33,62]};
C = cellfun(@minus,A,B,'uni',0)
C = 1×2 cell array
{[2 -36 -42 -54]} {[12 -4 -32]}
  3 comentarios
Ahmad Bayhaqi
Ahmad Bayhaqi el 5 de Jul. de 2021
in my case, the array :
A(2x1 cell)= {[32,28,30,31]} {[27,29,30]}
B(2x1 cell)={[30,64,72,85]}{[[15,33,62]}
Stephen23
Stephen23 el 5 de Jul. de 2021
Editada: Stephen23 el 5 de Jul. de 2021
It works for me:
A = {[32,28,30,31],[27,29,30]};
B = {[30,64,72,85],[15,33,62]};
C = cellfun(@minus,A,B,'uni',0)
C = 1×2 cell array
{[2 -36 -42 -54]} {[12 -4 -32]}
You would get that error if both your description and examples are incorrect, and you actually have nested cell arrays, e.g. in R2021b:
B = {{30,64,72,85},{15,33,62}};
C = cellfun(@minus,A,B,'uni',0)
Error using cellfun
Operator '-' is not supported for operands of type 'cell'.
Or in R2013b (note the error message text change):
>> C = cellfun(@minus,A,B,'uni',0)
Error using cellfun
Undefined function 'minus' for input arguments of type 'cell'.

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 5 de Jul. de 2021
Editada: Image Analyst el 5 de Jul. de 2021
Try a simple and intuitive for loop:
A = {[32,28,30,31],[27,29,30]}
B = {[30,64,72,85],[15,33,62]}
% A for loop works:
[rows, columns] = size(A)
for col = 1 : columns
C{col} = A{col} - B{col}
end
% Stephen's method also works, at least in R2021a.
C2 = cellfun(@minus,A,B,'uni',0)
Of course you could also check the dimensions and make sure they're the same before you subtract, and throw up a "friendly" error message if they don't match, rather than barf up a screen of red error messages.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by