user3769914
user3769914

Reputation: 1

Replacing elements of variable in Matlab

How can I replace every element in the variable data that is less than 0.5 with 0.

I tried this, but it's not working.

rng(110)
data= rand(1, 1e8);
tstart = tic;
count = (data<0.5);
replace = replacedata(data,count,0);
telapsed = toc(tstart);

Upvotes: 0

Views: 75

Answers (2)

Cecilia
Cecilia

Reputation: 4721

The method replacedata is for dataset variables. Your data matrix is a standard Matlab matrix created using rand. Therefore the replacedata function can't be used with it.

It is possible to create a dataset type variable from your matrix using mat2dataset, but as Dan explained in his answer, it is simpler to use logical indexing.

Upvotes: 2

Dan
Dan

Reputation: 45741

what is replacedata?? This is quite basic matlab using logical indexing like so:

data(data < 0.5) = 0

Or alternatively:

replace = data.*(data < 0.5)  %// This only works because you are replacing the value with 0 as Matlab automatically casts logical matrices to doubles when using arithmetic.

Upvotes: 2

Related Questions