2 views (last 30 days)

Show older comments

Walter Roberson
on 25 Jan 2020

for x=randi([1,999],1,100)

When you do that, x will be set to each scalar from the vector of length 100.

if x(i)>x(i+1)

because x will be a scalar, x(i) will not exist for i > 1

The way you have it at the moment with

for x=randi([1,999],100,1)

makes x equal to the entire random vector at one go, and x(i) then is defined. However, you are also randomizing the entire x vector in each iteration of the for i loop, and that is not going to get you any sensical answers.

You need a structure that is more like

for some many trials

x = random vector

for i = 1 : length(x)

do your swapping if appropriate

end

end

However, I have to wonder what the original question about swapping is. It looks to me like a question about the number of swaps that would be needed for a Bubble Sort. If so then you have the problem that your code does not implement a Bubble Sort: it only implements a single pass of a Bubble Sort but Bubble Sort requires multiple passes.

Kyle Donk
on 25 Jan 2020

Allen
on 25 Jan 2020

I think you are not understanding how for-loop indexing works. Essentially, they are setup using a variable to identify the index and an array of values that the index will cycle through by increasing the index shifting to the next element in the array. The index does not retain the entire array in memory, it only retains the last value. Thus your initial for-loop defines X as the index and a range of values from 100 to 1000, with increments of 100 (ie - [100,200,300,...,1000]). Each time you step through this loop the value of X is changed to the next value in this array. For example, the first iteration X=100, the second iteration X=200, and the final iteration X=1000.

More importantly, the use of your initial for-loop does not appear to have any effect on the answer, it only makes you find the same solution multiple times. This is why every value of Y appears to be the same.

Replacing your plot command with the following will show you a quick example of how to use a for-loop and that you are actually plotting the same answer multiple time.

axes % Not normally needed, but wanted to use the "hold on" command outside of the for-loop

hold on % A

for i=1:length(Y)

% Plots each element of Y individually by changing the index "i" each iteration

plot(X,Y(i),'o')

legend(sprintf('Iteration: %i',i)) % Creates a label to identify the current iteration

pause(1) % pause execution for 0.5 seconds in order to make the changes perceivable

end

Try setting breakpoints within your code and stepping through your code to see how the values are changing throughout its execution. Below are links to how to use for-loops and how to using debugging tools built into MATLAB.

https://www.youtube.com/watch?v=PdNY9n8lV1Y (debugging video tutorial)

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

Start Hunting!