필터 지우기
필터 지우기

Replacing elements in arrays

조회 수: 8 (최근 30일)
kale
kale 2023년 9월 7일
편집: Mrutyunjaya Hiremath 2023년 9월 7일
I have an array of 39 elements consisting of only two digits. Every time I start the program, these two digits change. I give an example:
Run 1: array = [25 25 25 26 25 26 26 26 26 ....]
Run 2: array = [22 22 29 22 29 29 22 29 29 ....]
I need to replace the smallest number with "-1" and the largest number with "1".
I did it this way with a loop and I am asking if this seems correct (to me is correct because it works) and if it can be done "better" than this:
array_replaced = zeros(1,39);
for i=1:length(array)
if ii == 39
if array(i) < array(i-1)
array_replaced(i) = -1;
else array_replaced(i) = 1;
end
else
if array(i) < array(i+1)
array(i) = -1;
else array(i) = 1;
end
end
end
Thanks!

답변 (2개)

Star Strider
Star Strider 2023년 9월 7일
I am not exactly certain what you want to do, what the nubmers are, or if you only want to replace one or all that meet the criteria.
Possibly these —
array = randi([21 29], 1, 10) % Create Vector
array = 1×10
28 27 23 22 26 26 25 25 27 24
array(array==min(array)) = -1
array = 1×10
28 27 23 -1 26 26 25 25 27 24
array(array==max(array)) = +1
array = 1×10
1 27 23 -1 26 26 25 25 27 24
.

Mrutyunjaya Hiremath
Mrutyunjaya Hiremath 2023년 9월 7일
편집: Mrutyunjaya Hiremath 2023년 9월 7일
Here is a more straightforward way to replace the smallest and largest numbers in the array using MATLAB's built-in functions min and max.
% Sample array
array = [25, 25, 25, 26, 25, 26, 26, 26, 26]; % Replace with your actual array
% Find the minimum and maximum values in the array
minVal = min(array);
maxVal = max(array);
% Replace the minimum values with -1 and the maximum values with 1
array(array == minVal) = -1;
array(array == maxVal) = 1;
disp(array);
-1 -1 -1 1 -1 1 1 1 1

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by