MATLAB: How to convert 1D array into 2D array

array manipulation

Hello All, This is my sample code:
img=imread('C:\Users\nitin\Documents\MATLAB\t8.png');
img=rgb2gray(img);
[i,j]=size(img);
[x,y]=find(img);
for p=1:i*i
x1(p)=mod(32+(19*p),i);
end
for q=1:j*j
y1(q)=mod(16+(13*q),j);
end
x1=x1';
y1=y1';
After executing the above piece of code, I got x1(64*1) 1D array and y1(64*1) 1D array as new coordinates. Now I want to convert x1 and y1 into (8*8) matrix with new coordinates i.e. (x1,y1). Please help.

Best Answer

There are a few things that are not quite right with what you're doing
1) you're using x and y as row, column respectively. Standard convention is that x is the horizontal coordinate (column) and y is the vertical coordinate (row).
2) the x1 and y1 you calculate go from 0 to height or width minus 1. matlab indexing starts at 1, not 0. You need to add 1 to your coordinates.
Anyway, you wouldn't need reshape if you'd kept your x, y, x1, and y1 the same shape as the image. An added bonus is that you wouldn't even need the loop:
[y, x] = ndgrid(1:size(img, 1), 1:size(img, 2)); %order is [y, x] or [row, column]
x1 = mod(32 + 19*x, size(img, 2));
y1 = mod(16 + 13*y, size(img, 1));
scrambledimage = img(sub2ind(size(img), y1+1, x1+1));