How to make a 3D Matrix
조회 수: 6 (최근 30일)
이전 댓글 표시
How to make a 3D Matrix that contains all ones in the first layer, all twos in the second layer and all threes in the third layer?
채택된 답변
Jon
2020년 9월 3일
편집: Jon
2020년 9월 3일
You can also do it like this, for example for a 2 by 4 by 3
A = ones(2,4,3).*reshape(1:3,1,1,3)
댓글 수: 4
Abdolkarim Mohammadi
2020년 9월 11일
A simple way to reach the matrix you wanted is to create a m-by-n-by-k array of ones and then multiply it by a 1-by-1-by-k array of 1 to k. The trick is to first create a 1-by-k array and then permute it to ge the so-called 1-by-1-by-k array. You can permute it in different ways, including the permute() function and reshape().
Jon
2020년 9월 14일
편집: Jon
2020년 9월 14일
You asked about what the reshape function does.
The reshape(1:3,1,1,3) The first argument 1:3 makes a 3 element row vector with elements [1, 2, 3]the second, third and fourth arguments specify that we want to turn this row vector into a 1 row, by 1 column, by 3 "page" array. So 1 goes in the 1,1,1 location of the first page, 2 goes into th 1,1,2 location on the second page and 3 goes into the 1,1,3 location on the third page. By shaping it this way the array dimension for the multiplication
ones(2,4,3).*reshape(1:3,1,1,3)
become "compatible". Please see https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html#:~:text=In%20the%20simplest%20cases%2C%20two,element%2Dwise%20operation%20or%20function.
Also type doc reshape on the command line to get documentation on the reshape function for further details
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!