Specific conditions for array elements

2 views (last 30 days)
Alexander Nee
Alexander Nee on 22 Aug 2021
Commented: Alexander Neeon 22 Aug 2021
Hello! Let's say that i have an array 5x5 filled with numbers from 1 to 20
A=randi(20,5);
How can i compute a new array B of the same size as the A with three conditions:
1. If the element of the array A is smaller than 10, B =9^2
2. If the element of the array A is equal to 10, B =0
3. If the element of the array A is higher than 10, B =20^0.5
Thank you,
Alex

Accepted Answer

Awais Saeed
Awais Saeed on 22 Aug 2021
Edited:Awais Saeed on 22 Aug 2021
Fairly simple
clc;clear;close
A=randi(20,5);
B = A;
% get indices
B1 = find(B == 10);
b2 = find(b> 10);
b3 = find(b <10);
% change values at those indices
B(B1) = 0;
B(B2) = 20^0.5;
B(B3) = 9^2;
3 Comments
Alexander Nee
Alexander Nee on 22 Aug 2021
Thank you! You greatly helped me!

Sign in to comment.

More Answers (1)

Simon Chan
Simon Chan on 22 Aug 2021
You may simply combine them together as follows:
B = (A>10)*(9^2)+(A==10)*0+(A<10)*(20^0.5);
1 Comment
Alexander Nee
Alexander Nee on 22 Aug 2021
亲爱的西蒙·陈(Simon Chan),
感谢您的答复!

Sign in to comment.

Community Treasure Hunt

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

开始狩猎!