reshaping data so that I can take sum of every 3 columns

2 ビュー (過去 30 日間)
Neesha
Neesha 2015 年 10 月 30 日
コメント済み: Neesha 2015 年 11 月 2 日
Hi All,
I have a dataset something similar to following
Name Location Nickname saleCost
rest1 east Reast1 [5, 7, 9 , 2, 5, 1, 9, 11, 1]
rest4 south Rsouth4 [12, 9, 2, 3, 5, 10, 11, 4, 4]
rest3 east Reast3 [20, 2, 2, 3, 20, 30, 1, 3, 7]
rest9 west Rwest9 [1, 9, 3, 33, 22, 10, 6, 6, 8]
Note that saleCost is a dataset as well and as number of columns which are multiple of 3.
I want to add up every 3 columns so my resultant dataset is as follow
Name Location Nickname saleCost
rest1 east Reast1 [21, 8, 21]
rest4 south Rsouth4 [23, 17, 19]
rest3 east Reast3 [24, 53, 11]
rest9 west Rwest9 [13, 65, 20]
I tried using reshape() but could not use it correctly. WHat are my options?
Thanks

採用された回答

Kelly Kearney
Kelly Kearney 2015 年 10 月 30 日
When you say you have a dataset, do you mean a dataset array? I'm assuming so for the moment:
Your data:
tmp = {...
'Name' 'Location' 'Nickname' 'saleCost'
'rest1' 'east' 'Reast1' [5, 7, 9 , 2, 5, 1, 9, 11, 1]
'rest4' 'south' 'Rsouth4' [12, 9, 2, 3, 5, 10, 11, 4, 4]
'rest3' 'east' 'Reast3' [20, 2, 2, 3, 20, 30, 1, 3, 7]
'rest9' 'west' 'Rwest9' [1, 9, 3, 33, 22, 10, 6, 6, 8]};
D = cell2dataset(tmp);
Reshape:
D.saleCost = reshape(sum(reshape(D.saleCost', 3, []),1), [], size(D.saleCost,1))'
D =
Name Location Nickname saleCost
'rest1' 'east' 'Reast1' 21 8 21
'rest4' 'south' 'Rsouth4' 23 18 19
'rest3' 'east' 'Reast3' 24 53 11
'rest9' 'west' 'Rwest9' 13 65 20
Pretty much the same as Jelin's answer, but all in one command. Note that this applies to the entire array saleCost; you shouldn't need to loop over rows.
  1 件のコメント
Neesha
Neesha 2015 年 11 月 2 日
Perfect, thanks a lot! It is dataset , not an array but it does work for me...

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

その他の回答 (1 件)

Jacky Jo
Jacky Jo 2015 年 10 月 30 日
Is that you want..
saleCost=[5, 7, 9 , 2, 5, 1, 9, 11, 1;...
12, 9, 2, 3, 5, 10, 11, 4, 4;...
20, 2, 2, 3, 20, 30, 1, 3, 7;...
1, 9, 3, 33, 22, 10, 6, 6, 8];
saleCost=reshape( reshape(saleCost',[],3) ,3,[]);
saleCost=reshape(sum(saleCost,1),3,[])'
  2 件のコメント
Neesha
Neesha 2015 年 10 月 30 日
Let me try what is the result. I do not want to lose context info i have as i have shown in resultant set.
Neesha
Neesha 2015 年 10 月 30 日
It did not work, first line created all in one row with bunch of data added with default values. Also as i tried to execute second row, it ran into memory error

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

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by