Using cumulative sum to create a symmetric n-dimensional array
Show older comments
I am trying to create a symmetric tensor of order 2, 3 and more using the below code.
n = 5;
mask = tril(ones(n));
posVecF = 0;
Order = 3; %order of tensor
for j = 2:Order
A0 = bsxfun(@times,ones(repelem(n,j)),mask);
posMatrix = cumsum(A0(:));
posMatrix = reshape(posMatrix,repelem(n,j));
posMatrix(A0==0) = 0; % Make lower triangular tensor
posMatrix = posMatrix+posMatrix'-diag(diag(posMatrix)); % Mirror the lower half of the triangular tensor
end
The expected and calculated 'posMatrix' for order 2 (j=2) using the below code is
1 2 3 4 5
2 6 7 8 9
3 7 10 11 12
4 8 11 13 14
5 9 12 14 15
For order 3 (j = 3), I expect my 'posMatrix' to be a 5x5x5 tensor
val(:,:,1) =
1 2 3 4 5
2 6 7 8 9
3 7 10 11 12
4 8 11 13 14
5 9 12 14 15
val(:,:,2) =
2 6 7 8 9
6 16 17 18 19
7 17 20 21 22
8 18 21 23 24
9 19 22 24 25
val(:,:,3) =
3 7 10 11 12
7 17 20 21 22
10 20 26 27 28
11 21 27 29 30
12 22 28 30 31
val(:,:,4) =
4 8 11 13 14
8 18 21 23 24
11 21 27 29 30
13 23 29 32 33
14 24 30 33 34
val(:,:,5) =
5 9 12 14 15
9 19 22 24 25
12 22 28 30 31
14 24 30 33 34
15 25 31 34 35
But this is not what I get. There is an issue in the line posMatrix = cumsum(A0(:)); for higher order and posMatrix = posMatrix+posMatrix'-diag(diag(posMatrix)); should be adjusted for any orders. I am struggling to find a solution for this problem here.
Accepted Answer
More Answers (0)
Categories
Find more on Annotations 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!