how to write Binary table in simple way ?
4 次查看(过去 30 天)
显示 更早的评论
Hi there,
1. How to create Binary code (like this one below) in a simple way?
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
2. how to print only the relevant rows like:
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
only the rows that has 2 bits that equal to 1.....
Thanks,
Henry
0 个评论
采纳的回答
Walter Roberson
2015-9-12
What happens if you use dec2bin(13) - '0' ?
A way to calculate how many values are set in a row is to sum() the row.
You should also investigate logical indexing
12 个评论
Walid KESSAL
2018-3-16
Here's how you can take care of that problem Mr.Henry Buck.
n=4; tab=[];
for i=0:(2^n-1)
table(i+1,:) = dec2bin(i,n);
tab = [tab;table(i+1,:)];
end
table = tab
the result is this
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/188423/image.png)
Walter Roberson
2019-7-28
That code is redundant: just assigning into table() is enough without needing to build that tab variable.
更多回答(1 个)
Pierre Bulens
2019-7-28
dec2bin function gives the table :
![binarytable.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/231646/binarytable.png)
to get the rows containing 2 bits equal to 1, use the sum function and logical indexing
![rows with 2 ones.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/231647/rows%20with%202%20ones.png)
the sum function gives the number of 1s in each row,
the '== 2' part selects the wanted rows
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!