フィルターのクリア

array summation with matrices of different size

1 回表示 (過去 30 日間)
Saad
Saad 2013 年 1 月 3 日
Dear All,
I would appreciate some help on this one please.
I am summing matrix elements in different arrays. Say we have 2 arrays:
Price=num2cell(1:10); Coupon=num2cell(1:10);
Price is a cell composed of different matrices. The same for Coupon.
Now the size of the matrices inside "Price" and "Coupon" are not always equal. Of course if I run a code similar to this...
for i=1:10
Price{1,i}+ coupon{1,i};
end
...I get an error which what you would expect because the first matrix of "Price" and "Coupon" are of different size, ....
Now I would like to run an If statement to say: if matrix sizes of Price and Coupon are similar then sum them, if they are not equal then drop that extra elements (at the end) and just sum the first elements. How can I do that please?
example to illustrate: size(Price{1,1})=size(Coupon{1,1})= (1000,1) size(Price{1,2})=(995,1) < size(Coupon{1,2})= (1000,1)
I would like to ignore the extra elements (at the end) of Coupon{1,2} and then sum the remaining elements (i.e. from 1:995) with Price{1,2}? How Can I do that please?
Thanks a lot
  1 件のコメント
Saad
Saad 2013 年 1 月 3 日
thanks a lot for your help
Regards

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2013 年 1 月 3 日
for K = 1:10
s1 = size(Price{K});
s2 = size(Coupon{K}};
common = min(s1,s2);
rc = common(1);
cc = common(2);
Price{K}(1:rc, 1:cc) = Price{K}(1:rc, 1:cc} + Coupon{K}(1:rc, 1:cc);
end
  1 件のコメント
Saad
Saad 2013 年 1 月 3 日
thanks a lot for your help
Regards

サインインしてコメントする。

その他の回答 (1 件)

Wayne King
Wayne King 2013 年 1 月 3 日
編集済み: Wayne King 2013 年 1 月 3 日
When you say "matrices" are they are always really Nx1 column vectors as your example shows? If so you can just do this
Price = cell(10,1);
Coupon = cell(10,1);
Price{1} = randn(995,1);
Coupon{1} = randn(1000,1);
minval = min(length(Price{1}),length(Coupon{1}));
Price{1} = Price{1}(1:minval);
Coupon{1} = Coupon{1}(1:minval);
summ = Price{1}+Coupon{1};
Obviously, you can embed the above in a for loop
for ii = 1:10
minval = min(length(Price{ii}),length(Coupon{ii}));
Price{ii} = Price{ii}(1:minval);
Coupon{ii} = Coupon{ii}(1:minval);
summz{ii} = Price{ii}+Coupon{ii};
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by