user2661122
user2661122

Reputation: 73

select a range of values from a matrix and swap them

I have a matrix and i want to select a range of elements. for example i want to select all the elements that are lower than 182 and swap/change them. does someone know an easy way or command to do this in matlab ?

thanx

Upvotes: 0

Views: 1632

Answers (3)

user2613077
user2613077

Reputation: 78

You may use loop like this:

   for i = 1:length(matrix(:,1))
        for j = 1:length(matrix(1,:))
            if matrix(i,j) < 182
               matrix(i,j) = NaN;
            end
        end
    end

Upvotes: 0

horchler
horchler

Reputation: 18484

Such things can usually be accomplished via logical indexing:

A = randn(1,100);
B = randn(size(A));
test = (A>1|A<0);   % For example, values that are greater than 1 or less than 0
A(test) = B(test);

or another example:

A = randn(1,100);
test = (A>1|A<0);
A(test) = randn(1,nnz(test));

or another:

A = randn(1,100);
A(A>1|A<0) = NaN;

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112669

Since you say "swap", I understand you mean a vector, not a matrix. You can do it as follows:

x = [ 1 34 66 22 200 55 301 ]; % data
[ values, ind ] = find(x<182);
x(ind) = x(ind(end:-1:1));

To simply replace them by another value such as NaN, do as follows. Note that this works also for matrices:

x = [ 1 34 66 22 200 55 301 ]; % data
x(x<182) = NaN;

Upvotes: 1

Related Questions