Specific conditions for array elements

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

 Respuesta aceptada

Awais Saeed
Awais Saeed el 22 de Ag. de 2021
Editada: Awais Saeed el 22 de Ag. de 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 comentarios

Many thanks for your clear explanation! Can you also help me with that. Now, we have the array B computed the above. Along with that, we have random array C.
C=rand(5);
Can i change the elements of the array C to zero, where the elements of the array B is equal to 81?
You are welcome.
C = rand(5)
% get indices where B = 81
C1 = find(B == 81);
% change values at those indices to zero
C(C1) = 0
Al Ne
Al Ne el 22 de Ag. de 2021
Thank you! You greatly helped me!

Iniciar sesión para comentar.

Más respuestas (1)

Simon Chan
Simon Chan el 22 de Ag. de 2021
You may simply combine them together as follows:
B = (A>10)*(9^2)+(A==10)*0+(A<10)*(20^0.5);

Categorías

Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.

Preguntada:

el 22 de Ag. de 2021

Comentada:

el 22 de Ag. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by