How to create a pyramid shaped 3D matrix ?

12 views (last 30 days)
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)=

Accepted Answer

Stephen23
Stephen23 on 27 Oct 2015
Edited: Stephen23 on 27 Oct 2015
Either:
  1. use a cell array, or
  2. 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
  3 Comments
Stephen23
Stephen23 on 30 Oct 2015
Edited: Stephen23 on 30 Oct 2015
What would you prefer to prealloate with, if not with zeros? If you want a different values, simply replace the zeros with that value (e.g. NaN):
M(M==0) = val
Jacky Jo
Jacky Jo on 30 Oct 2015
Yea... that is a good idea... Thanks a lot.

Sign in to comment.

More Answers (1)

John D'Errico
John D'Errico on 30 Oct 2015
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.
  1 Comment
Jacky Jo
Jacky Jo on 30 Oct 2015
okay.... I will keep this in my mind... thanks for your suggestion...

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices 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!