Vectorization or Looping?

1 回表示 (過去 30 日間)
Dave O
Dave O 2022 年 11 月 27 日
コメント済み: Dave O 2022 年 11 月 27 日
I'm trying to accomplish a task through vectorization rather than reverting to my old habit of looping. I have a table, T, imported from a text file. The table is comprised of a list of items with a variable number of subtotals associated with each item. Is it possible to return the sum of the subtotals for each item without looping?
For example, with T below:
Var1 Var2
Item 1 NaN
Subtotal 1 1.4
Subtotal 2 0.7
Subtotal 3 5.4
Item2 NaN
Subtotal 1 1.9
Item 3 NaN
Subtotal 1 2.4
Subtotal 2 3.6
Desired output:
v1 v2
Item 1 7.5
Item 2 1.9
Item 3 6.0
v1 = find(contains(T.Var1,'Item'));
v2 = ?
Thanks in advance to anyone who can help!
  2 件のコメント
Stephen23
Stephen23 2022 年 11 月 27 日
編集済み: Stephen23 2022 年 11 月 27 日
The data arrangement make this challenging. A much better arrangement of the table data would be like this:
item = [1;1;1;2;3;3];
subt = [1.4;0.7;5.4;1.9;2.4;3.6];
tbl = table(item,subt)
tbl = 6×2 table
item subt ____ ____ 1 1.4 1 0.7 1 5.4 2 1.9 3 2.4 3 3.6
Then your task is simple:
out = groupsummary(tbl,"item",@sum)
out = 3×3 table
item GroupCount fun1_subt ____ __________ _________ 1 3 7.5 2 1 1.9 3 2 6
Dave O
Dave O 2022 年 11 月 27 日
Thank-you for directing me towards the group summary. This is exactly the functionality I needed.

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

採用された回答

Image Analyst
Image Analyst 2022 年 11 月 27 日
You forgot to attach your table. No one is going to type all that in when you could just give it to us in a .mat or text file.
In the meantime, check out findgroups, groupsummary, grpstats, and splitapply
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
  1 件のコメント
Dave O
Dave O 2022 年 11 月 27 日
Thank-you for directing me to these functions. These are what I needed to accomplish my task.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by