How to create 2D sub arrays by sampling every n by n points
Show older comments
Hi, I want to create 2D sub arrays by sampling every n by n points. Specifically, I have an array with size of 280x280. I want to sample every 8 by 8 points and form a 3D array with size of (35,35,64).
Currently I am using loop (refer to below) which takes abut 0.25msec on my Laptop. I am wondering if there is a more elegent and faster way to create the 3D array by taking advantage of matlab internal indexing capability.
Thank you!
%%%%%
%A=rand(280,280);
A = double(imread('AT3_1m4_01.tif'));
A = A(1:1:280,1:1:280)/256;
B=zeros(35,35,64);
numIter=1000;
tic
for iter=1:numIter
for i=1:1:8
for j=1:1:8
indx1=(i-1)*8+j;
B(:,:,indx1)=A(i:8:end,j:8:end);
end
end
end
disp(toc/numIter);
figure(1); montage(B);
%%%%%%%%%%%%%%%%%%%%%%%%%%
Accepted Answer
More Answers (2)
Ridwan Alam
on 10 Dec 2019
B = reshape(A,35,35,[]);
2 Comments
Adam Danz
on 10 Dec 2019
The indexing isn't consecutive, though.
B(:,:,indx1)=A(i:8:end,j:8:end);
Adam Danz
on 10 Dec 2019
B = permute(A,dimorder) rearranges the dimensions of A. The loop in the OP's code is extracting every 8 rows and every 8 columns so it's not clear to me how permute() would help.
The iter-loop is completely unnecessary and is merely doing the same exact work 1000 times.
numIter=1000;
tic
% for iter=1:numIter Remove this line
for i=1:1:8
for j=1:1:8
indx1=(i-1)*8+j;
B(:,:,indx1)=A(i:8:end,j:8:end);
end
end
% end Remove this line
Removing that reduces the processing time to 0.000047 sec. Since you're indexing non-consecutively, the loop method (without the iter-loop) will be quite fast and I doubt an ugly vectorized approach will be faster.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!