What is the most efficient way to fill a 4D array?
Show older comments
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
Guillaume
on 13 Jun 2017
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)
Accepted Answer
More Answers (1)
Guillaume
on 13 Jun 2017
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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!