How can I avoid using FOR loops and the FIND command for multidimensional array indexing?

I would like to manipulate elements of multidimensional arrays. When working with large arrays, both using FOR loops and avoiding FOR loops by using the FIND function are computationally slow.
As an example, consider the following:
Suppose A is a 10x10x10 matrix as follows:
A=rand(10,10,10);
A(1,2,2)=2;
A(3,4,1)=2;
A(5,6,3)=2;
I would like to set the array elements whose value is 2 to zero. I avoid using FOR loops and use instead the FIND and IND2SUB commands:
I=find(A==2);
[u,v,w]=ind2sub(size(A),I);
A(u,v,w)=0;
For large data arrays, however, this method is computationally slow.

 Accepted Answer

An alternative to the FOR and IND2SUB commands is to use the logical NOT (~) operator. You could set the required data elements to zero simply by writing the following:
A=-2*(~(A-2))+A;
In fact, the quickest possible method could be to use the following line of code.
A(A == 2) = 0
For more information and examples of logical indexing, refer to the page titled "How Logical Arrays Are Used" in the MATLAB documentation.
Also, you may want to look at this documentation page.
Techniques for Improving Performance and Vectorizing Your MATLAB Code.

More Answers (0)

Products

Release

R2006b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!