Replacing elements in arrays
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponses (2)
Star Strider
le 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(array==min(array)) = -1
array(array==max(array)) = +1
.
0 commentaires
Mrutyunjaya Hiremath
le 7 Sep 2023
Modifié(e) : Mrutyunjaya Hiremath
le 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);
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!