Effacer les filtres
Effacer les filtres

How to subtract number inside cell

5 vues (au cours des 30 derniers jours)
Ahmad Bayhaqi
Ahmad Bayhaqi le 5 Juil 2021
Modifié(e) : Stephen23 le 5 Juil 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

Réponses (2)

Stephen23
Stephen23 le 5 Juil 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 commentaires
Ahmad Bayhaqi
Ahmad Bayhaqi le 5 Juil 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 le 5 Juil 2021
Modifié(e) : Stephen23 le 5 Juil 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'.

Connectez-vous pour commenter.


Image Analyst
Image Analyst le 5 Juil 2021
Modifié(e) : Image Analyst le 5 Juil 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.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by