How to subtract number inside cell

2 ビュー (過去 30 日間)
Ahmad Bayhaqi
Ahmad Bayhaqi 2021 年 7 月 5 日
編集済み: Stephen23 2021 年 7 月 5 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by