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);
댓글 수: 0
답변 (1개)
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
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
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!