How to filling a blank matrix with designated patterns using a single for loop?

10 views (last 30 days)
Hello everyone,
I am wondering how to fill a 17x17 all zeros matrix with a specific pattern. Specifically, I intially created a 17x17 zero matrix and I have a matrix whose size is 1x289 where 289 is a result of 17x17. In here, I want to fill in the all zero 17x17 matrix with the existed matrix(1x289) using the code below such that:
Matrix_A = zeros([17 17]);
ii = 1:17:289;
jj = 1:1:17;
for kk = 1:length(ii)
a = ii(kk);
b = jj(kk);
Matrix_A(17,b) = existed_matrix(:,a);
end
The logic of this algorithm above is that I start to fill in the matrix from bottom to top. As a result, the column 1 and column 2 in the 17th row will seperated by 16 numbers in the existed matrix. Please see the diagram below. However, by using the code above, I only can fill in the blank in the 17th row. This means that I have to create 17 different for loops in order to fill in all 17 rows with the exsited_matrix.
Is there anyway to fill in all 289 blanks using only 1 for loop? I know the only place we need to modify in the code is "Matrix_A('another variable',b) = existed_matrix(:,a). This is where I got stuck.
Please help,
Thank you
diagram.png

Accepted Answer

Steven Lord
Steven Lord on 7 Nov 2019
reshape your vector into a matrix of the appropriate size then flip the matrix. No for loop required.
If you're required (by a homework assignment, for example) to use a for loop, you could reshape then reverse each column in turn.

More Answers (1)

Anahi Bermudez
Anahi Bermudez on 7 Nov 2019
Matrix_A = zeros([17 17]);
ii = 17:-1:1;
for kk = 1:length(ii)
existed_matrix(:,kk) = ii;
ii=ii+17;
end
  2 Comments
Taoooooooooooo
Taoooooooooooo on 7 Nov 2019
Hi Anahi Bermudez,
I guess I did not make myself clear while I was asking questions. Basically, I want to fill in a 17x17 blank matrix by using the number from the existed_matrix in a way as shown in the diagram above in the question window. I am not trying to modify the exisited_matrix.
Sincerely,
Tao
Anahi Bermudez
Anahi Bermudez on 7 Nov 2019
Oh, so you need to define existed matrix
Matrix_A = zeros([17 17]);
ii = 1:17:289;
jj = 17:17:289;
existed_matrix=1:length(Matrix_A)^2;
for kk = 1:length(ii)
Matrix_A(:,kk) = existed_matrix(jj(kk):-1:ii(kk));
end
good luck :)

Sign in to comment.

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!