I try to convert this MATLAB code: From:
- https://github.com/gpeyre/2013-SIIMS-ot-splitting/blob/master/code/toolbox/%40staggered/interp.m
- https://github.com/gpeyre/2013-SIIMS-ot-splitting/blob/master/code/toolbox/interp_adj.m
(useful to compute some prox of some functions):
case 3 %% 3D field %% V = cat(4, ... U.M{1}(1:end-1,:,:) + U.M{1}(2:end,:,:), ... U.M{2}(:,1:end-1,:) + U.M{2}(:,2:end,:), ... U.M{3}(:,:,1:end-1) + U.M{3}(:,:,2:end)); case 4 %% 4D field %% V = cat(5, ... U.M{1}(1:end-1,:,:,:) + U.M{1}(2:end,:,:,:), ... U.M{2}(:,1:end-1,:,:) + U.M{2}(:,2:end,:,:), ... U.M{3}(:,:,1:end-1,:) + U.M{3}(:,:,2:end,:),... U.M{4}(:,:,:,1:end-1) + U.M{4}(:,:,:,2:end)); "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.
rank = 4; size = 30; baseDim = ConstantArray[size, rank]; U = Table[Array[Subscript[m, ##] &, ReplacePart[baseDim, k -> size + 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.
Here the '4' stand for the dimension where I would like to catenate, that do the same job as "Join". This is the intuition behind the Mathematica code above. In pure Mathematica for a Tensor with Rank 4 above the special case code can look like:
Join[U[[1]][[2 ;; , ;; , ;; , ;;]] + U[[1]][[;; -2, ;; , ;; , ;; ]], U[[2]][[ ;; , 2 ;; , ;; , ;;]] + U[[2]][[;; , ;; -2, ;; , ;; ]], U[[3]][[ ;; , ;; , 2 ;; , ;;]] + U[[3]][[;; , ;; , ;; -2, ;; ]], U[[4]][[ ;; , ;; , ;; , 2 ;;]] + U[[4]][[;; , ;; , ;; , ;; -2]], 5] [Edit] The solution based on the answer of @Henrik-Schumacher:
With[{all = ConstantArray[All, rank]}, Table[U[[k]][[Sequence @@ ReplacePart[all, k -> 2 ;;]]] + U[[k]][[Sequence @@ ReplacePart[all, k -> ;; -2]]], {k, 1, rank}] ]
Dimensions? $\endgroup$4 Subscript[m, 1, 1, 1, 1] + Subscript[m, 1, 1, 1, 2] + Subscript[m, 1, 1, 2, 1] + Subscript[m, 1, 2, 1, 1] + Subscript[m, 2, 1, 1, 1], which indicates the output is not the one you expect. This behavior can be simplified to the following:Join[{A[x]}, {A[x]}, 2], and your mistake will be even more obvious if you replacetmpwithtmp = RandomReal[1, {3, 3, 3, 3}];. $\endgroup$