kalle
kalle

Reputation: 435

Apply a 2D map to a 3D array in MATLAB

I have a 3D array of arbitrary size m x n x d where d is the dimension, in this case, a time point. I have a 2D mask of size m x n that I want to apply to the 3D stack, and in each instance in which the mask has a value of 1, to set the value of the corresponding index in the stack to nan. The way I am doing this so far is:

imageStack((mask == 1)) = nan;

However, when displaying an image from one dimension of the stack, i.e. imagesc(imageStack(:,:,1) after the process, it is clear that the mask has been applied. However, higher dimensions do not have this mask applied - it seems that is has only applied it to the first dimension and not the full stack of images. Am I missing something in my impelementation of the mask?

Upvotes: 0

Views: 584

Answers (2)

BayesianMonk
BayesianMonk

Reputation: 647

You can also use repmat to broadcast your mask to the 3rd dimension:

d=size(imageStack,3);
imageStack(repmat(mask==1,[1,1,d]))=nan;

Upvotes: 0

Ander Biguri
Ander Biguri

Reputation: 35525

First create a mask with NaNs, to make the job easier. Your mask may work but you haven't shared it.

masknan=mask==1; masknan(masknan)=nan;

Then, if you are in a 2016b or newer, you can use implicit expansion for the job.

image=imageStack.*masknan; % it will automatically broadcast to the 3rd dimension

Otherwise, use bsxfun

image=bsxfun(@times,imageStack,masknan);

Upvotes: 3

Related Questions