Replacing elements in arrays
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
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(array==min(array)) = -1
array(array==max(array)) = +1
.
0 个评论
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!