I try to convert this MATLAB code: From:
(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}]
]
Answer
Up to the final Join
which I don't understand, the following might help:
r = 4;
tmp = Array[Subscript[m, ##] &, ConstantArray[3, r]];
With[{idx = ConstantArray[All, r]},
Table[
tmp[[Sequence @@ ReplacePart[idx, i -> 2 ;;]]] +
tmp[[Sequence @@ ReplacePart[idx, i -> ;; -2]]],
{i, 1, r}]
]
or
Table[Map[2 MovingAverage[#, {1, 1}] &, tmp, {i - 1}], {i, 1, r}]
Comments
Post a Comment