How to create a pyramid shaped 3D matrix ?
15 次查看(过去 30 天)
显示 更早的评论
I have 3D matrix (in a pyramid shape) which has (1x1) element in it's first matrix frame. This will increase (i.e,the number of elements = 3x3,5x5,9x9,11x11,...etc) in upcoming frames using a for loop. A small demonstration has given below. Please recommend suitable way to build without using cell technique.
LorM = 5;
for l=0:LorM+1
Dlkm(:,:,l+1)=ones((2*l)+1);
end
The output should be get like following way (if its possible):
Dlkm(:,:,1)= 1
Dlkm(:,:,2)= 1 1 1
1 1 1
1 1 1
Dlkm(:,:,3)=1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1 and so on: Dlkm(:,:,4)=
Dlkm(:,:,5)=
Dlkm(:,:,6)=
采纳的回答
Stephen23
2015-10-27
编辑:Stephen23
2015-10-27
Either:
- use a cell array, or
- fill the other positions with some value such as 0 or NaN:
x = 3;
for k = x:-1:0 % Reverse sequence to preallocate array.
y = 2*k+1;
M(1:y,1:y,k+1) = 1;
end
>> M
M(:,:,1) =
1 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
M(:,:,2) =
1 1 1 0 0 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
M(:,:,3) =
1 1 1 1 1 0 0
1 1 1 1 1 0 0
1 1 1 1 1 0 0
1 1 1 1 1 0 0
1 1 1 1 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
M(:,:,4) =
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
更多回答(1 个)
John D'Errico
2015-10-30
You cannot have a non-rectangular matrix in MATLAB. Period. This applies to 2 dimensions, it applies to n dimensions. So a purely triangular matrix, that is not filled with zeros (or something) to fill out the rectangle cannot happen.
So every plane of a 3 dimensional matrix has the same number of rows and columns as every other plane.
You can do it using cell arrays of course, since any cell can contain essentially anything. Or you can fill the remainder with zeros, or perhaps NaNs as you desire. Or, you can use a struct to store each plane.
The only other possibility is that you can create an object of your own, where you define array indexing yourself. Even in this case, you would probably end up storing internally the various planes of the object in a cell array or a struct.
另请参阅
类别
在 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!