% Canonical decopmosition, Input rank R

for i1=0:1;for i2=0:1;for i3=0:1;
                A(i1+1,i2+1,i3+1)=i1+2*i2+4*i3;
            end;end;end;
T=tensor(A);
U(2,R)=1;U(1,1)=1; 
U=rand(size(U));
lam=[1;1]; for j=1:R;lam(j)=1;end
if R==1; lam=1; end
V=U; W=U; % initialising for ALS
a1=double(tenmat(T,1));
a2=double(tenmat(T,2));
a3=double(tenmat(T,3));
for j=1:50
    U=a1*pinv(khatrirao(W,V))';
    V=a2*pinv(khatrirao(W,U))';
    W=a3*pinv(khatrirao(V,U))';
end
S=ktensor(lam,U,V,W);
norm(full(T)-full(S)),pause
ap=cp_als(T,R);
cp=tensor(ap);
norm(full(T)-full(cp))