Arrays-matrices: Island area and perimeter | Matlab Examples

Matlab Tutorials | Examples

Practice 7:

Arrays-matrices: Island area and perimeter

The above figure illustrates an example of a 2D grid map of an island, where land is shown in green and the surrounding sea is shown in blue. This grid map can be represented by an n×n matrix where green squares are 1s and blue squares are 0s.

The matrix can be filled manually with INPUT statements if the user wishes to enter the data. An alternative approach could be the use of MAT files.

MAT files are used for saving MATLAB variables for later use, or for transferring them between computers. You can save your variables into a MAT file by giving the save command.


>> save(‘myvariables.mat’);
The contents of MAT files are retrieved into MATLAB

workspace by making use of the load command. Example: >> fileName= ‘grid1.mat’;
>> load(fileName);

Write a MATLAB program that will do the following jobs:
1. Ask the user if s/he wants to load the grid data from a MAT file.

  1. If the first letter of the answer is y or Y, ask for the name of the file and load it the file contents to memory.
  2. If the first letter of the answer is anything different, ask for each row of the grid one by one. Note that the first row defines the geometry of the n×n square grid. The number of entries in the first row is equal to the number of rows, and how many elements each subsequent row should have. Make sure that the following rows have the correct number of entries, otherwise ask for that row again. Also make sure that all entries are 0s or 1s, otherwise ask for that row again.
  3. Calculate and display the perimeter and the area of the island assuming each side of the square is 1 unit.



Leave a Reply

Your email address will not be published. Required fields are marked *