Is it possible to multiply elements in a matrix greater than a certain value without using a loop?

13 views (last 30 days)
For example is it possible to find all the values greater than 1 in matrix 1 and multiply all the values greater than 1 by 2, so that you get something like matrix 2 without using a loop? matrix1 = [1 2 3; 4 5 6; 7 8 9] matrix2 = [1 4 6; 8 10 12; 14 16 18]

Accepted Answer

KSSV
KSSV on 22 Feb 2016
Edited: KSSV on 22 Feb 2016
matrix1 = [1 2 3; 4 5 6; 7 8 9] ;
matrix2 = matrix1 ;
matrix2(matrix1>1) = matrix1(matrix1>1)*2 ;
matrix2 =
1 4 6
8 10 12
14 16 18

More Answers (1)

Stephen23
Stephen23 on 22 Feb 2016
Edited: Stephen23 on 22 Feb 2016
Method One: Simple exponent in just one line:
>> X = [1 2 3; 4 5 6; 7 8 9];
>> Y = X .* 2.^(X>1)
Y =
1 4 6
8 10 12
14 16 18
Method Two: Indexing together with multiply:
>> idx = X>1;
>> Y = X;
>> Y(idx) = 2*X(idx)
Y =
1 4 6
8 10 12
14 16 18

Community Treasure Hunt

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

Start Hunting!