Tensor product of 3 arrays

Viewed 35

I have an equation to count, that looks like this:

F(a,b) = sum(c=1...n, a*b*c[i])

I can count it this way:

for a=
  for b=
    for c=
    F(a,b)=F(a,b)+a*b*c
    end
  end
end

But I've heard, that on big arrays matlab "freezes" on nested loops. So I can do it this way:

a=(1:n)';
b=1:n2;
Fs=a*b;
for c=
   F=F+Fs*c;
end

But I want to solve this problem without any visible cycle. So I can create three orthogonal arrays of a,b,c tensor product them to get 3-D array, and then use sum function by third dimension.

a(:,1,1)=1:3;
b(1,:,1)=4:6;
c(1,1,:)=7:9;
d=tensorprod (a,b,2,1)
e=tensorprod (d,c);

But I ran into tensor multiplication problem in matlab. e has to be 3x3x3 array, but it is 3x3x1x1x3 array. It is correct and all, and even

g=sum(e,5);

returns matrix, but I don't understand why the third dimension has moved to the fifth

3 Answers

Based on your loop, this should give the desired sum.

a = 1:3;
b = 4:6;
c = 7:9;
F = a' * b * sum(c) 

F = 
    96   120   144
   192   240   288
   288   360   432

I'm not sure that a no loop version is better. Using a broadcast (Matlab took that from Fortran and numpy), you could do it without loop, but I think the java JIT compiler of matlab could give better results with simple loops, nevertheless, a no-loop version could be

n2=3;
n2=4;
n3=5;
a=1:n1;
b=1:n2;
Fs=a'.*b;
F=zeros(size(Fs))
for c=1:n3
   F=F+Fs*c;
end
# the broadcast : all dimensions equal to one will be duplicate
# for the other tensor : after that we contract the tensor along the 
# third dimension
F2 = sum(Fs(:,:,1) .* reshape(1:n3,1,1,5), 3)
norm(F2-F,2)

You can do this with vectors and a dot product (inner product):

a=1:3;
b=4:6;
c=7:9;
D=dot(a,b);
E=sum(D*c)

E =

   768
Related