Filter löschen
Filter löschen

How to subtract number inside cell

5 Ansichten (letzte 30 Tage)
Ahmad Bayhaqi
Ahmad Bayhaqi am 5 Jul. 2021
Bearbeitet: Stephen23 am 5 Jul. 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

Antworten (2)

Stephen23
Stephen23 am 5 Jul. 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 Kommentare
Ahmad Bayhaqi
Ahmad Bayhaqi am 5 Jul. 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 am 5 Jul. 2021
Bearbeitet: Stephen23 am 5 Jul. 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'.

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 5 Jul. 2021
Bearbeitet: Image Analyst am 5 Jul. 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.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by