Exploiting symmetry in multidimensional arrays

Dear all, In a symmetric matrix A of size [n,n], for two indices i and j such that 1<=i<=n and 1<=j<=n we have that A(i,j)=A(j,i). Suppose I know A(i,j) for i>=j how can I efficiently set A(j,i)?
More generally, if I have a hypercube A of size n^m, how can I, on the basis of A(i1,i2,...,im) with i1>=i2>=i3....>=im, set all A for all permutations of i1,i2,...,im instead of recalculating the entry for each permutation.
Thanks,

 Akzeptierte Antwort

Roger Stafford
Roger Stafford am 13 Jul. 2014

0 Stimmen

For a general m-dimensional n^m array, A, do this:
[I1,I2,...,Im] = ndgrid(1:n);
P = [I1(:),I2(:),...,Im(:)];
Q = sort(P,2,'descend');
A(sub2ind(size(P),P(:,1),P(:,2),...,P(:,m))) = ...
A(sub2ind(size(Q),Q(:,1),Q(:,2),...,Q(:,m)))
Note: The four three-dot ellipses (...) shown above (but not the one following the '=' sign) are to be filled in by the user.

4 Kommentare

without "..." it might look something like:
clear I;
[I{1:m}] = ndgrid(1:n);
P = reshape(cat(m+1,I{:}),[],m);
Q = sort(P,2,'descend');
A(:) = A(1+(Q-1)*(n.^(0:m-1)'));
EDIT: replaced sub2ind which can be too slow at times...
Patrick Mboma
Patrick Mboma am 14 Jul. 2014
Bearbeitet: Patrick Mboma am 14 Jul. 2014
@ Roger, What you suggest is very helpful but there is, I think, a mistake in what you wrote. I believe the last command should be
A(sub2ind(size(A),P(:,1),P(:,2),...,P(:,m))) = ...
A(sub2ind(size(A),Q(:,1),Q(:,2),...,Q(:,m)))
That is, I replaced size(P) and size(Q) with size(A);
other than that it seems to work. Basically, instead of replacing just the missing indexes, you replace the whole array.
Many thanks,
Patrick Mboma
Patrick Mboma am 14 Jul. 2014
Bearbeitet: Patrick Mboma am 14 Jul. 2014
@Alfonso What you suggest would really be neat and seems to work well in the two-dimensional case that I tested. I still need to investigate higher dimensions and the speed.
@Patrick. Yes, you are quite right. I should have used size(A). I must have had a mental black out at that point! :-)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 13 Jul. 2014

0 Stimmen

For a 2D array it's easy:
B = tril(A,-1)
A = B+B.'+diag(A);

Kategorien

Mehr zu Mathematics and Optimization finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by