Attempted to access a(2); index out of bounds because numel(a)=1

if i try to make a string 111100011 into 1111, 000, 11
function [indi] = SeparatePattern (a)
k=1;
for i=1:length(a)
while strcmp(a(i),a(i+1))
if strcmp(a(i),'0')
indi(1,k)='0';
else
indi(1,k)='1';
end
end
while a(i)~=a(i+1)
k=k+1;
end
end
why i keep getting an error
Attempted to access a(2); index out of bounds because numel(a)=1?

 Accepted Answer

a = '111100011';
indi = regexp(a,'0+|1+','match')

More Answers (1)

What exactly are you passing for "a" ? Are you invoking
t = SeparatePattern(111100011)
? If you are then you are passing a single decimal number (roughly one billion) to the function instead of a string. To pass a string in you would need to invoke
t = SeparatePattern('111100011')
Also take note that you loop "i" from 1 to the length of a. Consider the last iteration, when "i" has already become length(a), so a(i) is the final element in "a". Inside the "for" you have
while strcmp(a(i),a(i+1))
but if a(i) is the last element of "a", then a(i+1) is going to be past the last element of "a" and you would get exactly the kind of error you saw.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!