Specific conditions for array elements

조회 수: 2 (최근 30일)
Alexander Nee
Alexander Nee 2021년 8월 22일
댓글: Alexander Nee 2021년 8월 22일
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

채택된 답변

Awais Saeed
Awais Saeed 2021년 8월 22일
편집: Awais Saeed 2021년 8월 22일
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
Awais Saeed
Awais Saeed 2021년 8월 22일
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
Alexander Nee
Alexander Nee 2021년 8월 22일
Thank you! You greatly helped me!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Simon Chan
Simon Chan 2021년 8월 22일
You may simply combine them together as follows:
B = (A>10)*(9^2)+(A==10)*0+(A<10)*(20^0.5);
  댓글 수: 1
Alexander Nee
Alexander Nee 2021년 8월 22일
Dear Simon Chan,
Thanks for your response!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by