make a loop that orders an array in ascending order in matlab

To order an array in ascending order using a loop in MATLAB, you can use the bubble sort algorithm. Here's an example implementation:

main.m
arr = [5, 3, 1, 4, 2]; % example array
n = length(arr);

for i = 1:n-1
    for j = 1:n-i
        if arr(j) > arr(j+1)
            % swap adjacent elements
            temp = arr(j);
            arr(j) = arr(j+1);
            arr(j+1) = temp;
        end
    end
end

% print sorted array
arr
292 chars
17 lines

In this implementation, we use two nested for loops to compare adjacent elements and swap them if they are out of order. The inner loop runs n-i times, where i is the current iteration of the outer loop. This is because after each iteration of the outer loop, the largest element will be "bubbled up" to the end of the array, so we don't need to compare it again.

Note that there are more efficient sorting algorithms available, but the bubble sort is simple to understand and implement.

gistlibby LogSnag