How can I convert 1D array into 2D array

167 visualizzazioni (ultimi 30 giorni)
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.
  3 Commenti
Rik
Rik il 23 Feb 2017
What is it you want to do? x and y both contain 64 values, so you can convert both into 8x8 matrices. So how do you want to combine these two into one?
For changing the shape of a vector/matrix you can use the function reshape
Shafali
Shafali il 24 Feb 2017
Yes, I used the function "reshape", still no luck.

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 24 Feb 2017
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));
  4 Commenti
Shafali
Shafali il 1 Mar 2017
Ok, Thanks a lot Guillaume.
Sebastian Joseph
Sebastian Joseph il 6 Mag 2021
What if the case of extracting 2d from 1d for loop..??

Accedi per commentare.

Più risposte (1)

Jan
Jan il 23 Feb 2017
[i,j] = size(img);
x1 = mod(32 + 19* (1:i*i), i);
x1 = reshape(x1, 8, 8);
y1 = mod(16 + 13* (1:j*j), j);
y1 = reshape(y1, 8, 8);
The detail "i.e. (x1,y1)" is not clear to me.
  4 Commenti
Jan
Jan il 26 Feb 2017
Exactly, my answer does not work. I've posted it with the intention to clarify the question. See my:
The detail "i.e. (x1,y1)" is not clear to me.
I'm still not sure, what you, Shafali, are asking for, and hope, that Guillaume's answer helps you. If so, please accept his answer, or try to explain the problem with a small example of the input and the wanted result.
Shafali
Shafali il 28 Feb 2017
Done Sir. Guillaume's answer does, what I really wanted.

Accedi per commentare.

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by