Clear Filters
Clear Filters

Replacing elements in arrays

8 views (last 30 days)
kale
kale on 7 Sep 2023
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!

Answers (2)

Star Strider
Star Strider on 7 Sep 2023
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 on 7 Sep 2023
Edited: Mrutyunjaya Hiremath on 7 Sep 2023
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!