how to convert 2*2 matrix into 256*256 matrix using for loop.

2 views (last 30 days)
Suppose I have a matrix
b = [1 2 3
4 5 6
7 8 9]
and I want to extend this matrix like this
b = [ 1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9];
using for loop

Answers (1)

Stephen23
Stephen23 on 1 Feb 2016
Edited: Stephen23 on 1 Feb 2016
Just use repmat, it is much neater and faster than using a loop:
>> b = [1,2,3;4,5,6;7,8,9]
b =
1 2 3
4 5 6
7 8 9
>> R = 3;
>> C = 3;
>> repmat(b,R,C)
ans =
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
7 8 9 7 8 9 7 8 9
If you really want to use a slow loop, then try this:
S = size(b);
for r = (R-1)*S(1):-S(1):0
for c = (C-1)*S(2):-S(2):0
out(r+1:r+S(1),c+1:c+S(2)) = b;
end
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!