MATLAB: Cant Use Reshape Function with Randi or Randperm

reshape

Hi,
I am trying to generate a random number vector and use it as shown in below:
plaintextsamples = randi(65535,1,1000);
for h = 1:1000
%a = plaintextsamples(i);

plaintexttemp = dec2bin(plaintextsamples(h),16);
for k = 1:16
temp = plaintexttemp(k);
plaintext(k) = str2double(temp);
end
ciphertext = encrypt_func(plaintext);
In the 9th line, I call a function and this function contents another function with reshape operation:
function permboxout = permbox1func(permboxin_temp)
%%%%Block Cipher 1 Permutation
permutation1 = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16];
permboxin_temp = dec2bin(permboxin_temp);
permboxin = reshape(permboxin_temp',[1,16]);
for i = 1:16
permboxout(permutation1(i)) = permboxin(i);
end
Basically, I am using the plaintext value in the first code as the input of the permbox1func and plaintext is a random value of the plaintextsamples which is created with an randi or randperm function.
When I run it an error message is shown:
Error using reshape
To RESHAPE the number of elements must not change.
Error in permbox1func (line 5)
permboxin = reshape(permboxin_temp',[1,16]);
Error in encrypt_func (line 21)
permboxround1 = permbox1func(sboxround1); %permutation 2
Error in decrypt (line 9)
ciphertext = encrypt_func(plaintext);
When I disable the randi function and using the loop value itself:
for h = 1:1000
%a = plaintextsamples(i);
plaintexttemp = dec2bin(h,16);
for k = 1:16
temp = plaintexttemp(k);
plaintext(k) = str2double(temp);
end
ciphertext = encrypt_func(plaintext);
It works if h = 1:540 but the same error pop up if max limit of h is bigger than 550 or 560. I am really confused. Why the limit of a loop or randi function matters for reshape function? The shape should not change each time because I already declared that plaintext is a double vector with 16 elements.
Thanks for your help.

Best Answer

I found the error.
permboxin_temp = dec2bin(permboxin_temp);
When this line is used with randi, a double array is created rather than a char array. And the function converts each value to a 16 bit value. So, at the end, permboxin_temp ends up with being a 4x16 char array (input is 4 decimal values). I fixed it with the following modification:
b = 1;
for a = 1:4
permboxin_tempk(b:b+3) = dec2bin(permboxin_temp(a), 4);
b = b + 4;
end
It may not be the optimal solution, but it works!