I want to compare every matrix element to a constant then calculate a new matrix based on every case

15 views (last 30 days)
i have a matrix A=[ 1 2 3 4 5 ] and a constant b=3 . and i want to compare each element in that matrix with that constant b and calculate a new matrix based on every case .
if element in A<b then should do A*b
if element in A=>b then should do A+b and i want to calculate a new matrix like this :
C= [ A*b A*b A+b A+b A+b ].

Accepted Answer

Voss
Voss on 21 May 2022
Edited: Voss on 21 May 2022
Use logical indexing:
A = [ 1 2 3 4 5 ];
b = 3;
C = zeros(size(A));
C(A < b) = A(A < b)*b;
C(A >= b) = A(A >= b)+b;
disp(C);
3 6 6 7 8
(Or perhaps more clearly:)
C = zeros(size(A));
idx = A < b; % storing the logical index
C(idx) = A(idx)*b;
C(~idx) = A(~idx)+b;
disp(C);
3 6 6 7 8

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!