필터 지우기
필터 지우기

How to read and manipulate binary numbers?

조회 수: 3 (최근 30일)
Mark
Mark 2013년 7월 3일
Hi,
Im currently working with binary numbers within matlab, however they are read into my code as single numbers eg. 10001011 etc. However, I need to break up the code so I can examine different parts. Is there a way of breaking a single number into a 2 or more cell array.
For Example, starting with 10001011
broken up to a 1x4 array of [10 00 10 11]
Id appreciate any help, Thanks! Mark
  댓글 수: 2
Chad Gilbert
Chad Gilbert 2013년 7월 3일
I'm having trouble imagining why you would need to do this. Are you sure there's no place in your code earlier on (say, when you're reading these data) when it makes more sense to format these? E.g. "a = fscanf(fid,'%c%c',2);" or something of the sort?
Mark
Mark 2013년 7월 3일
Its involved in the crossover over section of a genetic algorithm where the binary coding is used to represent an individual chromosome and the splicing of two chromosomes can be used to create new 'children'

댓글을 달려면 로그인하십시오.

채택된 답변

Chad Gilbert
Chad Gilbert 2013년 7월 3일
편집: Chad Gilbert 2013년 7월 3일
Strictly speaking, this should do it:
>> a = [1 0 0 0 1 0 1 1];
>> b = 10*a(1:2:end) + a(2:2:end)
b =
10 0 10 11
Or, if you've got a string of 1's and 0's:
>> a = '10001011';
>> arrayfun(@(i)a(i:i+1),1:2:length(a),'uniformoutput',false)
ans =
'10' '00' '01' '11'
Note: both of these solutions assume that you have an even number of digits. They'll croak if you pass in an odd number of digits.
  댓글 수: 3
Muthu Annamalai
Muthu Annamalai 2013년 7월 3일
@Chad croaking is fixed (untested!) if you modify the line,
arrayfun(@(i)a(i:min(i+1,end)),1:2:length(a),'uniformoutput',false)
Chad Gilbert
Chad Gilbert 2013년 7월 3일
@Mark The first idea handles and outputs actual numeric values. Your interest in the "first digit of the second cell" makes me think you're actually interested in strings. In which case, the second answer might be more appropriate.
@Muthu - nice! A quick test confirms that your fix works.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Kevin
Kevin 2013년 7월 3일
편집: Kevin 2013년 7월 3일
a = [1 0 0 0 1 0 1 1]
for p=1:(size(a)-1)
b = [b strcat(num2str(a(p)),num2str(a(p+1)))]
end
That should feed zeros as double zeros
KD

Mark
Mark 2013년 7월 3일
Cheers guys

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by