{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# HW1 - 1a function[cost = cost(s s= floor(s if(s<=500 s>=0...

This preview shows pages 1–3. Sign up to view the full content.

1a. function [cost] = cost(s) s= floor(s); if (s<=500 && s>=0) cost=(400-(s-21).^2).*sin(s.*pi./6); else display( 'S must be between 0 and 500' ) end >> x=0:1:500; plot(x,cost(x),'ro'); title('cost as a function of f'); ylabel('cost'); xlabel('s') 1b. function [snew] = neighbor(s) if (s<=500 && s>=0) x= randi([max(s-25,0),min(s+25,500)]); while x == s %prevents neighborhood function from selection 's' again x= randi([max(s-25,0),min(s+25,500)]); end snew= x; else display( 's not in valid range' ); %'s' must be between 0 and 500 end 1c. function solution= RW(sinitial, maxiter) if (sinitial >= 0 && sinitial <= 500) solution = zeros(maxiter,5);

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
scurrent= sinitial; sbest= scurrent; COSTbest =cost(scurrent); for i=1:maxiter scurrent= neighbor(scurrent); COSTcurrent= cost(scurrent); if COSTcurrent<COSTbest COSTbest=COSTcurrent; sbest= scurrent; end solution(i,1)= i; solution(i,2)= scurrent; solution(i,3)= sbest; solution(i,4)= COSTcurrent; solution(i,5)= COSTbest; end else display( 's not in valid range' ); end 1d. function solution = RS(sinitial, maxiter) if (sinitial >= 0 && sinitial <= 500) solution = zeros(maxiter,5); snew= sinitial; sbest= snew; COSTnew= cost(snew); COSTbest= cost(snew); for i=1:maxiter x= randi([0,500]); %prevent S from staying the same while x == snew x= randi([0 500]); end stest= x; COSTtest= cost(stest); if COSTtest<COSTbest COSTbest= COSTtest; COSTnew= COSTtest; snew= stest; sbest= snew; end solution(i,1)= i; solution(i,2)= snew; solution(i,3)= sbest; solution(i,4)= COSTnew; solution(i,5)= COSTbest; end
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}