MATLAB: How to solve, index exceeds matrix dimensions

rsa

The error appears in this line(fprintf('\t%d',c1(o)))

Best Answer

The code that contains the problem is copied below from your pdf attachment. The error happens when 'o' becomes larger than the number of elements in 'c1'.
while(o<=over)
fprintf('\t%d',c1(o));
o=o+1;
end
The while-loop that comes before this only has 1 iteration because of the break at the end! Without the break, the while loop will never end because 'o' will always be 1 since you are not increasing that value within the loop.
Solution
This is how your last 2 while-loops should appear. The arrows show where I corrected your code.
while(o<=over);
m=m1(o);
diff=0;
if(m>n);
diff=m-n+1;
end
m=m-diff;
qm=dec2bin(e);
len=length(qm);
c=1;
xz=1;
while(xz<=len)
if(qm(xz)=='1')
c=mod(mod((c^2),n)*m,n);
elseif(qm(xz)=='0')
c=(mod(c^2,n));
end
xz=xz+1;
end
c1(o)=c;
o = o+1; % <----------------- here (remove the break)
end
o=1;
fprintf('\nThe encrypted message is \n');
while(o<=over)
fprintf('\t%d',c1(o));
o=o+1;
end
fprintf('\n') % <-------------------- here (add this)