Please provide insight and assistance with this issue I am having. I am new to Matlab, so any advice would be greatly appreciated.

1 visualización (últimos 30 días)
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);

Respuestas (1)

meghannmarie
meghannmarie el 6 de Oct. de 2019
Editada: meghannmarie el 6 de Oct. de 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)
  3 comentarios
Walter Roberson
Walter Roberson el 7 de Oct. de 2019
The for i = 1:5:binaryLength does traverse in increments of 5, but at any one point i refers to a single location, not to a stretch of 5 locations. Once you are at any one location, i:i+4 refers to the location along with the next 4 locations.
meghannmarie
meghannmarie el 7 de Oct. de 2019
The line binary(i:i+4) is saying for example if i = 1, binary(1:5) means to take element 1 through element 5 from the character array binary. The next iteration would be i = 6, or binary(6:10) which means to take element 6 through element 10 from the character array binary.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by