How to subtract number inside cell

5 次查看(过去 30 天)
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

回答(2 个)

Stephen23
Stephen23 2021-7-5
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 个评论
Ahmad Bayhaqi
Ahmad Bayhaqi 2021-7-5
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 2021-7-5
编辑:Stephen23 2021-7-5
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'.

请先登录,再进行评论。


Image Analyst
Image Analyst 2021-7-5
编辑:Image Analyst 2021-7-5
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.

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by