4

I have a 3 dimensional array (10x3x3) in Matlab and I want to change any value greater than 999 to Inf. However, I only want this to apply to (:,:,2:3) of this array.

All the help I have found online seems to only apply to the whole array, or 1 column of a 2D array. I can't work out how to apply this to a 3D array.

I have tried the following code, but it becomes a 69x3x3 array after I run it, and I don't really get why. I tried to copy the code from someone using a 2D array, so I just think I don't really understand what the code is doing.

A(A(:,:,2)>999,2)=Inf;
A(A(:,:,3)>999,3)=Inf;

1 Answer 1

3

One approach with logical indexing -

mask = A>999;  %// get the 3D mask
mask(:,:,1) = 0; %// set all elements in the first 3D slice to zeros, 
%// to neglect their effect when we mask the entire input array with it
A(mask) = Inf %// finally mask and set them to Infs

Another with linear indexing -

idx = find(A>999); %// Find linear indices that match the criteria
valid_idx = idx(idx>size(A,1)*size(A,2)) %// Select indices from 2nd 3D slice onwards
A(valid_idx)=Inf %// Set to Infs

Or yet another with linear indexing, almost same as the previous one with the valid index being calculated in one step and thus enabling us a one-liner -

A(find(A(:,:,2:3)>999) + size(A,1)*size(A,2))=Inf
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. They all worked brilliantly. I especially like the one-liner!
@emmalgale Me too! Exploring through the approaches led to that final one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.