Question

In matlab I have a matrix with random numbers between 0 and 100. All numbers below 10 shall be multiplicated by two.

testmatrix = [1,2;11,90] should turn into [2,4;11,90]

Executing conditional operations on the matrix is easy enough, but how do I reference the current element on the right side?

testmatrix(testmatrix<10) = ???*2

Was it helpful?

Solution

In exactly the same way as on the left hand side:

testmatrix(testmatrix<10) = testmatrix(testmatrix<10)*2

Or as Amro points out, you can save on computations by creating a reusable logical indexing mask:

idx = testmatrix < 10
testmatrix(idx) = testmatrix(idx)*2

This second approach is particularly useful in more cases with more complex conditions or where the condition is repeated many times or when speed is a major concern

OTHER TIPS

What you need is:

testmatrix(testmatrix < 10) = testmatrix(testmatrix < 10)*2;

How about this:

A = randi(100,1000,1);

cond = A <= 10;

test = A(cond).*2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top