MATLAB Answers

I have a timetable with 10 columns that are all binary and I want to add them together so I get a sum of those binary numbers for each row. Is there an easy way to do this?

5 ビュー (過去 30 日間)
GS25
GS25 2020 年 4 月 24 日
編集済み: Peter Perkins 2020 年 4 月 27 日
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
0 1 0 0 1 0 1 0 1 1
this is a copy and paste of the timetable, but it has nearly 2 million rows so I want to find an easy way to do this! Thanks in advance.

  1 件のコメント

Walter Roberson
Walter Roberson 2020 年 4 月 25 日
By "sum" do you mean that you want to know the number of non-zero elements in each row?
Or do you want "sum" to mean according to boolean logic where addition corresponds to "or", and so the result would be 1 if any bit was set and 0 otherwise?
Or do you want "sum" to mean according to xor logic, 0+0 -> 0, 0+1 -> 1, 1+0 -> 1, 1+1 -> 0, and so the result would be 1 if an odd number of bits was set and 0 otherwise?

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

採用された回答

Peter Perkins
Peter Perkins 2020 年 4 月 27 日
編集済み: Peter Perkins 2020 年 4 月 27 日
There are several ways to do this, here's one particularly simple one. Assuming you are starting with something like this ...
>> tt1 = array2timetable(randi([0 1],5,3),'rowTimes',seconds(1:5))
tt1 =
5×3 timetable
Time Var1 Var2 Var3
_____ ____ ____ ____
1 sec 1 1 1
2 sec 0 1 0
3 sec 1 0 1
4 sec 1 0 0
5 sec 1 0 1
... then combine the vars into one, and sum across rows.
>> tt2 = mergevars(tt1,1:3)
tt2 =
5×1 timetable
Time Var1
_____ ___________
1 sec 1 1 1
2 sec 0 1 0
3 sec 1 0 1
4 sec 1 0 0
5 sec 1 0 1
>> tt2.Var1 = sum(tt2.Var1,2)
tt2 =
5×1 timetable
Time Var1
_____ ____
1 sec 3
2 sec 1
3 sec 2
4 sec 1
5 sec 2
Or maybe you want to keep the individual vars around:
>> tt1.Var4 = sum(tt1{:,:},2)
tt1 =
5×4 timetable
Time Var1 Var2 Var3 Var4
_____ ____ ____ ____ ____
1 sec 1 1 1 3
2 sec 0 1 0 1
3 sec 1 0 1 2
4 sec 1 0 0 1
5 sec 1 0 1 2

  0 件のコメント

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

その他の回答 (1 件)

Sindar
Sindar 2020 年 4 月 25 日
% example table
mytable=array2table(randi([0 1],20,10));
% create column variable with sum
sum_all = sum(mytable{:,1:10},2);
% add sum column to table
mytable.sum_all = sum(mytable{:,1:10},2);

  0 件のコメント

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

Community Treasure Hunt

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

Start Hunting!

Translated by