case 3 %% 3D field %% V = cat(4, ... U.M{1}(1:end-1,:,:) + U(2:end,:,:), ... U.M{2}(:,1:end-1,:) + U(:,2:end,:), ... U.M{3}(:,:,1:end-1) + U(:,:,2:end)); case 4 %% 4D field %% V = cat(5, ... U.M{1}(1:end-1,:,:,:) + U(2:end,:,:,:), ... U.M{2}(:,1:end-1,:,:) + U(:,2:end,:,:), ... U.M{3}(:,:,1:end-1,:) + U(:,:,2:end,:),... U.M{4}(:,:,:,1:end-1) + U(:,:,:,2:end));
I"The dimension of U.M{1} is (N+1,N) while that of U.M{2} is (N,N+1) for 2D field". I would like to have the same behavior on Mathematica, without a switch case, on arbitrary dimension. I try to do some mix with Take, Drop, ... Without any success. The behavior should be close to:
tmp = Array[Subscript[m, ##] &, {3, 3, 3, 3}]; rank = Length[Dimensions[tmp]];3; Vsize = Table[30; tmp[[Span@Table[If[pbaseDim === kConstantArray[size, 2rank]; U ;;,= All]Table[Array[Subscript[m, {p,##] 1&, rank}]]] + tmp[[Span@Table[If[p == kReplacePart[baseDim, ;;k -2, All],> {p,size 1,+ rank}]]]1]], {k, 1, rank}];
The idea of the MATLAB code is to concatenate N sub-tensor by taking the begining of and the end of each dimension and sum them up. What we do here for the first dimension:
U(1:end-1,:,:) + U(2:end,:,:)
For the second one
U(:,1:end-1,:) + U(:,2:end,:)
And so on, after concatenating all of them:
cat(4, ... U(1:end-1,:,:) + U(2:end,:,:), ... U(:,1:end-1,:) + U(:,2:end,:), ... U(:,:,1:end-1) + U(:,:,2:end))
tmp = Array[Subscript[m, ##] &, {3, 3, 3, 3}]; Join[tmp[[2Join[U[[1]][[2 ;; , ;; , ;; , ;;]] + tmp[[;;U[[1]]tmp[[;; -2, ;; , ;; , ;; ]], tmp[[U[[2]][[ ;; , 2 ;; , ;; , ;;]] + tmp[[;;U[[2]][[;; , ;; -2, ;; , ;; ]], tmp[[U[[3]][[ ;; , ;; , 2 ;; , ;;]] + tmp[[;;U[[3]][[;; , ;; , ;; -2, ;; ]], tmp[[U[[4]][[ ;; , ;; , ;; , 2 ;;]] + tmp[[;;U[[4]][[;; , ;; , ;; , ;; -2]], 5]
[Edit] The solution based on the answer of @Henrik-Schumacher:
With[{all = ConstantArray[All, rank]}, Table[tmp[[k]][[Sequence @@ ReplacePart[all, k -> 2 ;;]]] + tmp[[k]][[Sequence @@ ReplacePart[all, k -> ;; -2]]], {k, 1, rank}] ]