for loop only through certain elements of an array
8 views (last 30 days)
Show older comments
Hello all,
I would like to do this more time efficiently. Lets say I have a 4D (xn,yn,zn,N) data array and a 3D (xn,yn,zn) mask array. I would like to go through 4D array and calculate something from the numbers in the 4th dimension, but I want only elements from the mask. Is there a way of doing this more efficiently, than going through xn*yn*zn elements and checking if they are withing the mask?
This is the brute force way:
for x=1:xn
for y=1:yn
for z=1:zn
if mask(x,y,z)==1
do something with data(x,y,z,:);
end
end
end
end
Thank you.
Edit: I think I need to explain the task at hand better. The 4D data is several 3D images combined along the 4th dimension, which corresponds to certain image acquisition parameters. I want to do
f=fit(Par, data(x,y,z,:), 'exp1');
for each image voxel from the mask.
6 Comments
Image Analyst
on 23 Nov 2017
So you're doing something like this:
for k = 1 : xn*yn*zn
if mask(k)
% do something with data(x,y,z,:);
% Now need x, y, and z so need to use ind2sub().
[x, y, z] = ind2sub(size(data), k);
thisData = data(x, y, z);
end
end
Note that arrays not not normally indexed as (x, y, z) though. They're indexed (row, column, z) which is (y, x, z). So the above code just assumes that x is the row, which is fine, just realize that it's not the x as you usually think of it.
Answers (1)
Image Analyst
on 22 Nov 2017
Try looping over the 4th dimension
for n = 1 : N
this3DArray = data(:,:,:,n);
dataOnlyWithInMask = this3DArray(mask); % 1-D vector.
% Now do something with dataOnlyWithInMask .
end
2 Comments
Image Analyst
on 22 Nov 2017
If it's something like a video where you have color images, and then a bunch of them over time, then you need to extract just one pixel's color channel over time. So you'd do this:
redChannelOverTime = squeeze(data(y, x, 1, :));
Note how y and x area flipped because y is rows which is the first index. I think this will provide a 1-D array along the time dimension. Then do whatever fitting you want to it.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!