Asked by xRobot
on 6 Oct 2019

This is my code. I am trying to read through the input string five digits at a time. The input will always be a multiple of 5 e.g. "000001000010000". Each specific 5 digit sequence will be assigned a letter 'A', 'B', etc. and appended to chararacter vector "output" and displayed at the end. I am having trouble making my program read the first 5 digits then the next 5 digits....and so on. I am able to loop through entire sequence successfully reading only the first 5 digits but I am having trouble continuing to check the set of 5 digits successively. Could you please provide insight on what various methods could resolve my issue. Thanks!

binary = input('Enter binary sequence: ','s');

output = '';

binaryLength = strlength(binary);

i=1;

while binaryLength

for i = binary(i:i+4)

if binary(i) == '00000'

output = strcat(output,'A');

elseif binary(i) == '00001'

output = strcat(output,'B');

end

end

i = i+1;

binaryLength = binaryLength -5;

end

disp(output);

Answer by meghannmarie
on 6 Oct 2019

Edited by meghannmarie
on 6 Oct 2019

You do not need the while loop, you can just use the for loop starting at 1 to string length in increments of 5. You also want to use strcmp for testing string equality.

binary = input('Enter binary sequence: ','s');

output = '';

binaryLength = strlength(binary);

for i = 1:5:binaryLength

if strcmp(binary(i:(i+4)),'00000')

output = strcat(output,'A');

elseif strcmp(binary(i:(i+4)),'00001')

output = strcat(output,'B');

end

end

disp(output)

Or you could do this without loop:

binary = input('Enter binary sequence: ','s');

output = cellstr(reshape(binary,5,[])');

output(contains(output,'00000')) = {'A'};

output(contains(output,'00001')) = {'B'};

output = cell2mat(output');

disp(output)

xRobot
on 7 Oct 2019

Walter Roberson
on 7 Oct 2019

meghannmarie
on 7 Oct 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.