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

2 次查看(过去 30 天)
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);

回答(1 个)

meghannmarie
meghannmarie 2019-10-6
编辑:meghannmarie 2019-10-6
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 个评论
Walter Roberson
Walter Roberson 2019-10-7
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 2019-10-7
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by