小言_互联网的博客

非线性优化1 随机搜索

246人阅读  评论(0)

Introduction:

In this lab, I had done some practices about basic structures and operations of MATLAB what I had learnt in last semester. By reviewing these efficient tips on using MATLAB, my ability to program in MATLAB had been improved. 

Solutions and Analysis:

Lab1.1:

In this problem, I just use a variable called varargin to read all uncertain variables. Then we can do a for loop to get the sum of these input variables. The function that can sum all input is shown as following:

function [Sum]=SumALL(varargin) 

Sum=0;

for i=1:nargin

Sum=Sum+varargin{i};

end

end

 

Then we can use an example to verify this function. By obverting the result of the function. We can find that the function is right.

 

Lab1.2:

This problem is verifying the random search algorithm. The principle of this algorithm is just add a random increment, and judge or compare whether the increment is suitable.

The result of this algorithm is:

Lab1.3:

Exercise1:

This excise is using MATLAB to construct a simple database, and achieve four basic operations in database like insert, delete, list and clear. For this problem, I use structure and some basic operation in files.

The code of the function called people was shown like following:

function people(db_file,operation,varargin) % beacause the number of the input is unceartain

switch operation       %use switch to jundge the input opeartion

    case 'reset'       %clear opeartion

        delete('db_file.mat');

    case 'list'        %just load all terms in the file and display all terms with some special format

        load('db_file.mat');

        [~,b]=size(person);

         for k=1:b 

            disp(['Name: ',person(k).Name,' Age:', num2str(person(k).Age)]);

         end

    case 'insert'       % insert some new terms

      

        j=1;

        i=1;

         while(i<=nargin-3) %record the people who need to be inserted in the list

            person(j) = struct('Name', varargin{i}, 'Age',varargin{i+1});

            i=i+2;

            j=j+1;

          end

       save('db_file.mat', 'person')

    case 'remove'      % delete some terms in the list

        j=1;

        i=1;

         while(i<=nargin-3) %record the terms which need to be deleted in the database

            DeletedPeople(j) = struct('Name', varargin{i}, 'Age',varargin{i+1});

            i=i+2;

            j=j+1;

          end

        load('db_file');

        [a,b]=size(person);

        count =0;

        check=zeros(1,20);% this array is to record if this person had been deleted.

        for k=1:b

             for p=1:((nargin-2)/2+1)

              if(p>=(nargin-2)/2+1)

                  p1=0;

                  p2=0;

              else

              p1=(strcmp(person(k).Name, DeletedPeople(p).Name ));

              p2=(person(k).Age== DeletedPeople(p).Age);

              end

                if p1&&p2  % Only when name and age are both equal to the people we want to delete, check will change.

                    check(k)=1;

                end

            end

        end 

        for  k=1:b

            if check(k)~=1

                new(k-count)=person(k); %if the check not equal to one, this indicate that this peeson had not been deleted

            else

                count=count+1;

            end

        end

            person=new;

       save('db_file.mat''person')

end

end

 

The result of this function is:

We can find that the result is right.

 

Exercise2:

The purpose of this exercise is rotating the polygon, we can use some basic math knowledge to get the transform matrix. The brief process of finding matric was shown in this figure:

By this matrix, we can rotate any polygon conveniently.

The code of this exercise was shown as this:

function RotatePlygon(inputAngle)

 X = [-5 -3 -4 2 1 8 6 3];

 Y = [-6 0 10 8 2 3 -5 -2];

 figure

 plot(X,Y);

 title('b');

 hSquare = fill(X,Y,'k');

 thetad  = 1;

 R = [cosd(thetad) -sind(thetad); sind(thetad) cosd(thetad)];

 C = repmat([0 0], 8, 1)';

 axis([-15 15 -15 15])

  for k=1:inputAngle

     V = get(hSquare,'Vertices')';  % get the current set of vertices

     V = R*(V - C) + C;             % do the rotation relative to the centre of the square

     set(hSquare,'Vertices',V');    % update the vertices

     pause(0.01);

  end

end

Then we can test this function’

Figure 1 The original figure

Figure 2 The figure rotated 20 degrees

Exercise3:

For this problem, we can find this maze is a kind of graph. The problem description asked us to find the shortest path to through the maze. Apparently this problem is an easy shortest path problem. We can use some classical algorithm to get the solution. But this problem is not as easy as we imaged. And I haven’t found a very good algorithm to solve this problem.

The reasons why I think this problem is difficult are:

  1. The maze may construct a loop; we need to judge whether the graph has a loop. Otherwise our algorithm will go wrong.
  2. The positions of entrances and exits are arbitrary position that is not an obstacle. These position will increase our computation.

At last, I use a naive way which is using DFS to every pair of entrance and exit. And by this method, we can get all doable ways, we can find the shortest way.

We can also use BFS and SPFA.

In DFS, we can use stacks to store data, but I don’t have enough time to do that.

 

This function is to span the maze to big matrices with different entrances and exits.

function [AllMaze]=GenerateAllMaze(maze)

 [n,n]= size(maze);

 NumOfEntrance=0;

 NumOfExit=0;

        for i =1:n

            if (maze(1,i)~=1)

                NumOfEntrance=NumOfEntrance+1;

            end

             if (maze(n,i)~=1)

                 NumOfExit=NumOfExit+1;

            end

        end    

        k=0;

for i=1:n

    maze = [0 1 0 0 1

        0 1 1 0 1

        0 1 0 0 1

        0 1 1 0 1

         0 1 0 0 0];

    if(maze(1,i)~=1)

      maze(1,i)=2;

      for j=1:n

        if(maze(n,j)~=1)

          maze(n,j)=3;

          k=k+1;

          AllMaze(:,:,k)=maze;

          maze(n,j)=0;

        end

      end

    end

end

end

 

Then we will write the DFS.

function [Solution, PathLength]=DFS_Maze(maze,InputSolution,InputShortestPathLength)

% This function can get all path f the mazze by using DFS

% maze: 0 represents that this point can go

%       1 represents that this point is obstacles

%       2 represents that this point is the entrance of this maze

%       3 represents that this point is the exit of this maze

%       5 represents that this point is on the path which was found in this

%       time

%             0 2 0 0 1

%             0 1 1 0 1

%             0 1 0 0 1

%             0 1 0 0 1

 

 

% Defined the four directions

directions = kron(eye(2),[-1,1]);

% The number of the path which were found in this time

NumberOfPath = 0;

% Find the entrance for this time

[I,J] = find(maze == 2);

[Solution,PathLength]=search(I,J);

%disp(NumberOfPath);

% Jundge whether the point can pass

    function z = WhetherGo(x,y)

        % I use a constructure called try to jundge

        z = true;

        try

            % jundge whether this point is a obstacal or the point which we had passed

            if ismember(maze(x,y),[1,2,5])

                z = false;

            end

        catch

            z = false;

        end

    end

 

    function [Solution,PathLength]=search(x,y)

        if maze(x,y) == 3 % Find the exit for this maze

            disp(maze);   % print the path

            NumberOfPath = NumberOfPath + 1;

            PathLength=length(find(maze==5))+1;

            disp(PathLength);

            Solution=maze;

            return

        else

            PathLength=10;

            Solution=maze;

        end

        

        % Search four different directions

        for i = 1 : 4

            if WhetherGo(x + directions(1,i),y + directions(2,i))

                if maze(x + directions(1,i),y + directions(2,i)) ~= 3

                    maze(x + directions(1,i),y + directions(2,i)) = 5;

            

                end

                search(x + directions(1,i),y + directions(2,i)); % countine to find 

                if maze(x + directions(1,i),y + directions(2,i)) ~= 3

                    maze(x + directions(1,i),y + directions(2,i)) = 0; % come back to this point and find another direction

                end

            end

        end

    end

end

 

 

 

 

Then we can test our program.

We can find that the program is right.


转载:https://blog.csdn.net/zzx2015/article/details/102488138
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场