Is it possible to multiply elements in a matrix greater than a certain value without using a loop?
13 views (last 30 days)
Show older comments
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]
0 Comments
Accepted Answer
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
1 Comment
Wolfgang McCormack
on 18 Jan 2021
Hi, how can I ask MATLAB to only multiply the numbers greater than 1 in second column?
More Answers (1)
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
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!