forked from AMGoldsborough/TNR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtfuse.m
More file actions
83 lines (63 loc) · 2.19 KB
/
Copy pathtfuse.m
File metadata and controls
83 lines (63 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function [B] = tfuse(A,Aid)
% [B] = tfuse(A,Aid)
% Function to fuse legs of a tensor.
% input: Tensor A with desired final indices Aid where positive labels will be joined.
% output: Tensor B which is A with appropriate legs fused
% tfuse - Andrew Goldsborough 05/09/2012
% based on tcon function
% example of Aid: [4,-1,-3,-2,4] will output a tensor with legs in the
% order of the absolute value, with the two legs labeled '4' fused.
%tic
%check that there are no zero indices
zeroidxA = find(Aid==0);
sizezeroidxA = size(zeroidxA);
if sizezeroidxA(2) ~= 0
fprintf('index cannot equal zero\n');
error('tcon:zeroidx', 'zero index detected');
end
%get size of arrays
sizeAid = size(Aid);
sizeA = size(A);
%check that the size of A matches the size of Aid
if (size(sizeA,2) ~= sizeAid(2))
error('tfuse:sizeAid','number of entries in Aid must match dimension of A');
end
%check that the unfused indices are not repeated
if (size(find(Aid<0),2) ~= 0) && (isequal(sort(Aid(find(Aid<0))), unique(Aid(find(Aid<0)))) ~= 1)
fprintf('unfused index numbers must be unique\n');
error('tfuse:Aidxunique','repeated unfused index detected');
end
%flip fused indices to match my index convention
% A = permute(A,sizeAid(2):-1:1);
% Aid = fliplr(Aid);
%sort in increasing order keeping the ordering index array
[Aid,Aidoix] = sort(Aid);
%permute indices st the indices to be fused are on the right
A = permute(A,Aidoix);
%get size of new A
sizeA = size(A);
%need the number of negative indices
negidxA = find(Aid<0);
numnegA = size(negidxA);
%flip fused indices to match my index convention
% A = permute(A,sizeAid(2):-1:1);
% Aid = fliplr(Aid);
A = permute(A,[1:numnegA(2),sizeAid(2):-1:(numnegA(2)+1)]);
%[1:numnegA(2),sizeAid(2):-1:(numnegA(2)+1)]
%need the size of the fused indices (u)
sizeu = prod(sizeA((numnegA(2)+1):end));
%if not fully flatened
if (size(find(Aid<0),2) ~= 0)
%fuse indices
sizeA2 = cat(2,sizeA(1:numnegA(2)),sizeu);
A2 = reshape(A,sizeA2);
%permute to desired form
[Bid,Bidoix] = sort(abs(unique(Aid)));
B = permute(A2,Bidoix);
else
%fuse indices
sizeA2 = cat(2,sizeA(1:numnegA(2)),sizeu);
A2 = reshape(A,sizeA2,1);
B = A2;
end
%toc