% IAP 2006 Introduction to MATLAB
% Interface and Basics

% EXAMPLE 1 Massachusetts Census Data
% A. Data Input and Output

% A1. Data Import Using Editor
% Load census data for MA counties from file MA_2000_county_data.txt
% From File menu, select Import Data... to open the Import WIzard.
% Select file MA_2000_county_data.txt and accept defaults. 
% Numbers get imported into the matrix data, which is a 14x9 double array.
% Text gets imported into the matrix textdata, which is a 15x10 cell array.
% Display the elements of the matrix data:
data

% A2. Vectors
% Note: you may use shorter names for the vectors.
% Create a vector with the names of the 14 counties in MA:
counties = textdata(2:15, 1)
% Create a vector of county areas:
area = data(:, 1)
% Create vectors with county population by race or ethnicity:
White = data(:, 2)
Black = data(:, 3)
Asian = data(:, 4)
Other = data(:, 5)
Hispanic = data(:, 6)
% Create vectors with county population by gender:
Males = data(:, 7)
Females = data(:, 8)
% Create a vector with total county population:
Population = data(:, 9)

% A3. Matrices
% Create a matrix with county population of all races
races = data(:, 2:5)
% Alternatively:
races = [White Black Asian Other]
% Create a matrix with county population of both genders:
genders = data(:, 7:8)
% Alternatively:
genders = [Males Females]

% A4. Matrix Operators
% Addition
allraces = White + Black + Asian + Other
allpeople = Males + Females
% A test of calculation for total number of people per county.
% The columns in the matrix TestTotalNumber must be identical.
TestTotalNumber = [allraces allpeople Population]
% Substraction
NonHispanic = allraces - Hispanic
% Division and multiplication
% Error: density = Population/area; must use . operator! 
density = Population ./ area
percentRaces = [White./Population  Black./Population   Asian./Population ...
    Other./Population]*100
percentGender = [Males./Population   Females./Population]*100

% A5. Data Analysis Using Built-In Functions
% Summation
MAresidents = sum(data)
MAraces = sum(races)
MAgenders = sum(genders)
% Test of total number of people
MApeople = sum(MAraces) 
MApeople = sum(MAgenders)
% Mean and standard deviation
meanByGender = mean(genders)
stdByGender = std(genders)
meanByRace = mean(races)
stdByRace = std(races)

% A6. Variables
% Test what variables have been created so far
whos

% A7. Data Output
% Create a matrix with percentile results:
Percentile = [percentRaces percentGender]
% Export percentile matrix to a text file:
save 'MA_county_percents.txt' Percentile -ascii

% A8. Import Data Using Built-In Function load
Percents = load('MA_county_percents.txt')
