フィルターのクリア

Summing two binary vectors

46 ビュー (過去 30 日間)
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 24 日
コメント済み: Adam Danz 2021 年 3 月 25 日
How can I add two binary vector say a= 1 0 1, b= 1 1 0?
Using simply '+' gives decimal output. I want the summation in binary.

採用された回答

Fangjun Jiang
Fangjun Jiang 2021 年 3 月 24 日
編集済み: Fangjun Jiang 2021 年 3 月 24 日
%%
a = [1 0 1];
b = [1 1 0];
s=dec2bin(bin2dec(num2str(a))+bin2dec(num2str(b)))
out=str2num(s(:))
out =
1
0
1
1
  1 件のコメント
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 25 日
That worked. Thanks

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

その他の回答 (1 件)

Adam Danz
Adam Danz 2021 年 3 月 24 日
編集済み: Adam Danz 2021 年 3 月 24 日
y = sumbin(a,b) adds two binary values a and b represented by boolean row vectors (1/0, true/false) and returns the results y as a boolean row vector.
log2dec(v) is a helper function called by sumbin() and converts the boolean vectors to binary strings and then to the decimal representation.
Demo:
a = [1 0 1]; % = 5
b = [1 1 0]; % = 6
log2dec = @(v)bin2dec(num2str(v));
sumbin = @(a,b)dec2bin(sum([log2dec(a), log2dec(b)]))-'0';
sumbin(a,b) % = 11
ans = 1×4
1 0 1 1
If you want to add more than 2 binary numbers in the form of boolean vectors,
y = sumbin(a,b,...,n) receives any number of boolean row vectors (1/0, true/false) and returns the results y as a boolean row vector.
a = [1 0 1]; % = 5
b = [1 1 0]; % = 6
c = [1]; % = 1
d = [1 1 1]; % = 7
log2dec = @(v)bin2dec(num2str(v));
sumbin = @(varargin)dec2bin(sum(cellfun(log2dec, varargin)))-'0';
sumbin(a,b,c,d) % = 19
ans = 1×5
1 0 0 1 1
  2 件のコメント
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 25 日
Hello Adam. Thanks for answering. Also I want to say sorry coz before I didn't knew the difference between array and vectors (I know that sounds stupid). Your answer is based on vector I think but I wanted to know about array. Sorry I am new to matlab. But anyway, thanks for answering. I got to know something new here
Adam Danz
Adam Danz 2021 年 3 月 25 日
@Neeraj Chimwal just FYI, the first part of my answer and Fangjun Jiang's answer are practically the same, there's very little difference.
The second part of my answer shows how to extend the summation to more than 2 binary vectors.
All vectors are arrays but not all arrays are vectors. A vector is 2D with one dimention equal to 1.
These are vectors
A = [1 0 1];
size(A)
ans = 1×2
1 3
B = [1;0;1];
size(B)
ans = 1×2
3 1
These are arrays that are not vectors
C = rand(2,3);
size(C)
ans = 1×2
2 3
D = rand(2,3,4);
size(D)
ans = 1×3
2 3 4

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by