Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
You will be estimating the number of swaps required for a list that is X=100, 200, 300, ..., 900, and 1000 numbers long. In other words, you will calculate an average for each number from 100 to 1000 in steps of 100. Each average should be calculat
조회 수: 1 (최근 30일)
이전 댓글 표시
x=[];
numsteps=0;
for N=[100]
for i=1:N
x=[x,floor(999*rand(1)+1)];
end
for i=1:N-1
for j=1:N-i
if (x(j)>x(j+1))
temp=x(j);
x(j)=x(j+1);
x(j+1)=temp;
numsteps= numsteps + 1;
end
end
end
end
fprintf('the number of steps is %d\n', numsteps);
This is my code. I need it to loop again for different values of n like 200, 300, 400...1000. also need it to display the number of steps for each n. I just cant figure out how to have it loop back with a different number of n. Please help?
댓글 수: 0
답변 (1개)
Rik
2020년 1월 24일
You probably want to use randperm to generate the random list. If you don't want to, you should preallocate the x vector and fill it using indexing.
The source of your problem is that you aren't treating this like a function. Try to rewrite this so you can put in a value for N at the beginning and get numsteps out at the end. Once you have done that, it is easy to put the entire thing in a for loop like this:
for N=100:100:1000
%your updated code
fprintf('For N=%d, the number of steps is %d\n',N,numsteps);
end
Since this is homework I'm not going to give you a copy-paste solution, but feel free to ask for additional hints and/or clarification.
댓글 수: 3
Rik
2020년 1월 24일
This is what happens with only a few minor edits to your code:
N=100;
numsteps=0;
x=zeros(N,1);
for ind1=1:N
x(ind1)=floor(999*rand(1)+1);
end
for ind1=1:N-1
for ind2=1:N-ind1
if (x(ind2)>x(ind2+1))
temp=x(ind2);
x(ind2)=x(ind2+1);
x(ind2+1)=temp;
numsteps= numsteps + 1;
end
end
end
fprintf('the number of steps is %d\n', numsteps);
Now you have no warning left from m-lint, and you are most of the way to a solution to your homework.
The assignment wants you to find the average number of steps, which you haven't done yet. This code only finds the number of steps for one particular random vector. Also, the answer is not for N=1000, but for N=100.
Since you essentially have a function here, you only need to find the average number of steps for a given N, and to repeat that process for different values of N.
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!