Replacing elements in arrays

11 次查看(过去 30 天)
kale
kale 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
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