## Apply a mask to 4D medical images in a vectorized way

on 11 Feb 2013

### José-Luis (view profile)

Dear All,

I have a 4D array V, with the size [144 144 12 25]. In fact, it is a 4D medical image with 12 stacked slices in 25 different time. I want to apply a mask, named M, to each image in the array in a vectorized way. M is a 144x144 array containing logical values. Could someone help me how to do it?

Thanks,

José-Luis

on 11 Feb 2013

## Products

No products are associated with this question.

### José-Luis (view profile)

on 11 Feb 2013
Edited by José-Luis

### José-Luis (view profile)

on 12 Feb 2013

``` data = rand(144,144,12,25);

Assuming you want to multiply by the mask:

` your_result = bsxfun(@times,data,mask);`

Note that you can do operations other than multiplication. Please have a look at

` doc bsxfun`

Sean de Wolski

### Sean de Wolski (view profile)

on 11 Feb 2013

Isn't that what you want?

+1

AP

### AP (view profile)

on 11 Feb 2013

I want the operation on each image. I thought bsxfun is only for each pixel and can't be applied to each image in a 4D array. Please correct me if I am wrong: so when we call bsxfun(@times,data,mask), bsxfun applies the mask to each 144x144. Is that right?

José-Luis

### José-Luis (view profile)

on 12 Feb 2013

Yes. That's what the "singleton expansion" in the documentation means.

on 11 Feb 2013

Something like this:

```fV = V.*M(:,:,ones(1,size(V,3)),ones(1,size(V,4)));
```

AP

### AP (view profile)

on 11 Feb 2013

How can I convert M, with size [144 144] to M with [144 144 12 25]?

AP

### AP (view profile)

on 11 Feb 2013

I think, I have to use

```repmat(M, [1 1 size(V,3) size(V,4)])
```

to duplicate M in other dimensions and make it [144 144 12 25].

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi