I want to compare every matrix element to a constant then calculate a new matrix based on every case
15 views (last 30 days)
Show older comments
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 ].
0 Comments
Accepted Answer
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);
(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);
2 Comments
More Answers (0)
See Also
Categories
Find more on Cell Arrays 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!