How to filling a blank matrix with designated patterns using a single for loop?
7 次查看(过去 30 天)
显示 更早的评论
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/247290/diagram.png)
0 个评论
采纳的回答
Steven Lord
2019-11-7
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.
0 个评论
更多回答(1 个)
Anahi Bermudez
2019-11-7
Matrix_A = zeros([17 17]);
ii = 17:-1:1;
for kk = 1:length(ii)
existed_matrix(:,kk) = ii;
ii=ii+17;
end
2 个评论
Anahi Bermudez
2019-11-7
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 :)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!