What is the most efficient way to fill a 4D array?

I would like to fill a 4D array as follows, give a 4D array shift1:
newShift(j,k,l,1:3) = constant + [j k l] + shift1(j,k,l,1:3)
The dimensions of the array are approx. 150 x 150 x 150 x 3, so it would take a very long time to do this in a nested loop. (I will need to recalculate this multiple time, so I need a method which takes << 1 sec, ideally).
Is there a more efficient method? Thanks!
Mark W

1 Comment

Should that be
newShift(j,k,l,1:3) = constant + permute([j k l], [2 3 4 1]) + shift1(j,k,l,1:3)
otherwise the expression is not valid (<R2016b) or produces a lot more than 3 elements (R2016b or later)

Sign in to comment.

 Accepted Answer

Matt J
Matt J on 13 Jun 2017
Edited: Matt J on 13 Jun 2017
You would pre-compute this once,
[J,K,L]=ndgrid(1:150);
offset=constant+cat(4,J,K,L);
and then for each new shift1, you compute
newshift=offset+shift1;
On my machine this takes about .2 sec on the CPU and 1.3e-4 sec. as a gpuArray.

More Answers (1)

Assuming your [j k l] is supposed to be in the 4th dimension:
[rows, cols, pages] = ndgrid(1:size(shift1, 1), 1:size(shift1, 2), 1:size(shift1, 3));
newshift = constant + cat(4, rows, cols, pages) + shift1;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 13 Jun 2017

Answered:

on 13 Jun 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!