Raldenors
Raldenors

Reputation: 311

How to display zero if your variable is less than 1, using Matlab

I have some raw data stored into a matrix like so:

A = [1     2   0.05    5
0.01 0.02  1      1
0.09  1    1      1];

I would like A to change so that those values less than 1 become zero automatically, so something like:

A = [1     2   0      5
0     0   1      1
0     1   1      1];

Is there a way to do this in MATLAB?

Upvotes: 3

Views: 81

Answers (1)

rayryeng
rayryeng

Reputation: 104514

If the data is in a matrix... call it A, it's as simple as:

A(A < 1) = 0;

As proof, let's declare that data and store it into A:

A = [1 2 0.05 5;
     0.01 0.02 1 1;
     0.09 1 1 1];

A(A < 1) = 0

A =

     1     2     0     5
     0     0     1     1
     0     1     1     1

The moral of this story is that logical indexing is your friend and ally in the MATLAB universe. More information about it can be found here: http://blogs.mathworks.com/steve/2008/01/28/logical-indexing/ - Steve Eddins from MathWorks makes a wonderful case about it.

Upvotes: 5

Related Questions