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

22 ビュー (過去 30 日間)
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 ].

採用された回答

Voss
Voss 2022 年 5 月 21 日
編集済み: Voss 2022 年 5 月 21 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by