GithubHelp home page GithubHelp logo

fagan2888 / m4econ Goto Github PK

View Code? Open in Web Editor NEW

This project forked from fanwangecon/m4econ

0.0 1.0 0.0 25.06 MB

Matlab Code Examples

Home Page: https://fanwangecon.github.io/M4Econ/

MATLAB 99.29% Objective-C 0.03% TeX 0.68%

m4econ's Introduction

HitCount Star Fork Star DOI

This is a work-in-progress website consisting of Matlab example code for manipulating various data structures, dynamic programming, graphing and associated tasks.

bookdown site and bookdown pdf.

Materials gathered from various projects in which matlab is used. Matlab files are linked below by section with livescript files. Tested with Matlab 2019a. This is not a Matlab package, but a list of examples in PDF/HTML/Mlx formats. MEconTools is a package that can be installed with tools used in projects involving matlab code.

Bullet points in the Appendix show which matlab functions/commands are used to achieve various objectives. The goal of this repository is to make it easier to find/re-use codes produced for various projects. Some functions also rely on or correspond to functions from MEconTools [@M-MEconTools].

From other repositories: For dynamic borrowing and savings problems, see Dynamic Asset Repository; For code examples, see also R Example Code, and Stata Example Code; For intro stat with R, see Intro Statistics for Undergraduates, and intro Math with Matlab, see Intro Mathematics for Economists. See here for all of Fan's public repositories.

Please contact FanWangEcon for issues or problems.

1 Data Structures

1.1 Matrices and Arrays

  1. Array Reshape, Repeat and Expand: mlx | m | pdf | html
    • Reshape and flatten arrays.
    • m: reshape()
  2. Array Index Slicing and Subsetting to Replace and Expand: mlx | m | pdf | html
    • Index based column and row expansions.
    • Anonymous function to slice array subsets.
    • m: sub2ind() + @(it_subset_n, it_ar_n) unique(round(((0:1:(it_subset_n-1))/(it_subset_n-1)) times (it_ar_n-1)+1))
  3. Find the Maximum Value and Index in Matrix Over Columns and Overall: mlx | m | pdf | html
    • Given 2D array, find the maximum value and index for each column.
    • Find the maximum value in a 2D array's row and column indexes.
    • m: max() + ind2sub() + maxk()
  4. Array Broadcasting Examples: mlx | m | pdf | html
    • broadcast means: array + array’ + matrix = matrix.
  5. Grid States, Choices and Optimal Choices Example: mlx | m | pdf | html
    • States, choices, and find max.
  6. Accumarray Examples: mlx | m | pdf | html
    • Accumarray to sum up probabilities/values for discrete elements of arrays.
    • m: unique() + reshape() + accumarray()
  7. Array Random Draws and Permutation: mlx | m | pdf | html
    • Draw randomly from array, permutate arrays.
    • m: ndgrid() + cell2mat(cellfun(@(m) m(:), cl_mt_all, 'uni', 0))
  8. Matlab Array Miscellaneous: mlx | m | pdf | html
    • Check data/parameter types.
    • Compare approximately similar values.
    • Find imaginary elements of array.
    • m: imag() + isfloat() + iscell()

1.2 ND Dimensional Arrays

  1. 3D, 4D, ND Arrays Reshape and Summarize: mlx | m | pdf | html
    • Slice 2D matrixes out of ND matrixes. The 2D matrix is contiguous, but can be intermediate dimensions.
    • Summarize a nd dimensional matrix along one or two dimensions group by various other dimensions.
    • m: permute(mn, [3,1,2,4]) + squeeze(num2cell(mn, [1,2])) + celldisp() + ndgrid()
  2. ND Array Drop NaN Elements Reshape to 2D Dataframe with Variable Values: mlx | m | pdf | html
    • There is a ND Array where each dimension is a different attribute, generate 2D dataframe with columns for attribute values and ND Array values stored as a single column.
    • There might be many NaN values in the ND array, drop NaN values in the ND array for 2D dataframe. Find the non-NaN values along each index dimension.
    • m: cell() + NaN() + isnan() + ind2sub() + find()

1.3 Cells

  1. List Comprehension with Cells: mlx | m | pdf | html
    • Cell2mat, cellfun, anonymous function list comprehension over cells.
    • Find min and max of all arrays in cells.
    • Find length of all arrays in cells; find index of elements of one array in another cell array.
    • m: cell2mat() + cellfun() + strcmp() + find() + cell2mat(cellfun(@(m) find(strcmp(ls_st_param_key, m)), cl_st_param_keys, ‘UniformOutput’, false))
  2. Permutate Cells: mlx | m | pdf | html
    • Generate all possible combinations of various arrays contained in cell array.
    • m: ndgrid() + cell2mat() + array2table() + cell2mat(cellfun(@(m) m(:), cl_mt_all, ‘uni’, 0))
  3. Combine Cells: mlx | m | pdf | html
    • Combine string cell arrays and string.
    • m: [{st_param}, ls_st_param_key, cl_st_param_keys]
  4. Nested Cells: mlx | m | pdf | html
    • Cell of cells with inner cell having multiple types.
    • m: linspace() + cell([4,1]) + clns_parm_tstar{1} = {‘fl_crra’, ‘CRRA’, linspace(1, 2, it_simu_vec_len)} + disp(clns_parm_tstar(1)) + disp(clns_parm_tstar{1}{1})

1.4 Characters and Strings

  1. String Basics: mlx | m | pdf | html
    • Compose string and rounded numeric array.
    • Cut string suffix and append new suffix.
    • m: compose() + strjoin() + str_sub = split(string, ".") + strcat(str_sub{1}, '_m.m')
  2. String Arrays Operations: mlx | m | pdf | html
    • String arrays and cell strings.
    • Duplicate strings, concatenate string, and paste strings jointly with separator.
    • Find string element positions, replace substrings.
    • m: repmat() + num2str() + strcat() + strjoin() + fprintf() + strcmp() + strrep() + cel2mat(cellfun(@(m) find(strcmp())))
  3. String and Numeric Array Concatenations: mlx | m | pdf | html
    • Generate rounded string array matrix with leading zero, leading space, decimal round from numeric matrix.
    • Create a title string by joining rounded parameter and parameter names.
    • Concatenate multiple numeric arrays together with strings and format.
    • m: compose() + cellstr() + strcat() + strjoin() + %.2f

1.5 Map Containers

  1. Container Map Basics: mlx | m | pdf | html
    • Numeric container map, dynamically filled container map.
    • m: isKey() + strjoin() + containers.Map('KeyType', 'char', 'ValueType', 'any')
  2. Display Container Map Keys, Values and Subseting: mlx | m | pdf | html
    • Loop over map, display keys and values.
    • Select Container map subset by keys.
    • m: strjoin() + keys(map) + values(map) + containers.Map(keys, values)
  3. Container Map Varied Value Type: mlx | m | pdf | html
    • Numeric scalar, string, matrix as values for map container.
    • Get values for multiple keys in map.
    • m: map.keys() + map.values() + values(param_map, {'share_unbanked_j', 'equi_r_j'})
  4. Cell Override: mlx | m | pdf | html
    • Override default map with externally fed map, update existing and add new keys.
    • m: param_map_updated = [param_map_old; param_map_updates_new]

2 Functions

2.1 varargin Default Parameters

  1. Use varargin as a Function Parameter: mlx | m | pdf | html
    • Default parameters allow for maintaining code testability.
    • Use varargin for functions with limited parameters.
    • m: varargin + cell2mat() + function [out_put] = func_name(varargin)
  2. Use varargin as a Function Parameter: mlx | m | pdf | html
    • The varargin structure could lead to excessive code lines. Container Map works well with large parameter structure.
    • Core model functions with potentially many parameters, possibly override default generation to save time.
    • m: varargin + function [out_put] = func_name(varargin) + cm_defaults = {cm_a, cm_b} + [cm_defaults{1:optional_params_len}] = varargin{:} + cm_c = [cm_a;cm_b]

3 Panel

3.1 Time Series

  1. Autoregressive Process AR(1): mlx | m | pdf | html
    • The Mean and standard deviation of an AR(1) process.
    • Simulate and graph an AR(1) persistent process.
    • Simulate log income process with parameters estimated from Indian income data.
    • m: normrnd() + for it_t=1:1:length(ar_shk) + plot(ar_t, ar_y)

4 Simulation

4.1 Normal Distribution

  1. Compute CDF for Normal and Bivariate Normal Distributions: mlx | m | pdf | html
    • CDF for normal random variable through simulation and with NORMCDF function.
    • CDF for bivariate normal random variables through simulation and with NORMCDF function, using cholesky deomposition to model correlation from uniform random draws.
    • m: mvncdf + norminv
  2. Cholesky Decomposition Correlated Two Dimensional Normal Shock: mlx | m | pdf | html
    • Draw two correlated normal shocks using the MVNRND function.
    • Draw two correlated normal shocks from uniform random variables using Cholesky Decomposition.
    • m: mvnrnd + corrcoef + norminv
  3. Cholesky Decomposition Correlated Five Dimensional Normal Shock: mlx | m | pdf | html
    • Generate variance-covariance matrix from correlation and standard deviation.
    • Draw five correlated normal shocks using the MVNRND function.
    • Draw five correlated normal shocks from uniform random variables using Cholesky Decomposition.
    • m: mvnrnd + corrcoef + norminv + subplot

5 Graphs

5.1 Figure Components

  1. Image Pick Safe Colors: mlx | m | pdf | html
    • Display safe colors.
    • m: blue = [57 106 177]./255 + fill(x, y, cl_colors{it_color})
  2. Figure Titling and Legend: mlx | m | pdf | html
    • Multi-line titles, add legend lines.
    • Add to legend, select legend to show.
    • m: title({'Cash-on-Hand' '$\alpha + \beta = \zeta$'},'Interpreter','latex') + legend([g1, g2, g3], {'near','linear','spline'}, 'Location', 'best', 'NumColumns', 1, 'FontSize', 12, 'TextColor', 'black');
  3. Graph Many Lines Legend for Subset: mlx | m | pdf | html
    • State-space plots with color spectrum: can not show all states in legend, show subset, add additional line to plot and legend.
    • m: jet() + numel() + fliplr() + jet(numel(chart)), set(chart(m), 'Color', clr(m,:))

5.2 Basic Figure Types

  1. Scatter Plot Examples: mlx | m | pdf | html
    • Scatter multiple lines different colors, shapes and sizes.
    • m: scatter(x, y, size) + Marker + MarkerEdgeColor + MarkerEdgeAlpha + MarkerFaceColor + MarkerFaceAlpha
  2. Scatter Plot Examples: mlx | m | pdf | html
    • Scatter and lines multiple lines different colors, shapes and sizes.
    • X axis, Y axis, and 45 degree line.
    • m: xline(0) + yline(0) + refline([1 0]) + plot(x,y) + HandleVisibility + Color + LineStyle + LineWidth
  3. Three variables Scatter and Lines with Color Spectrum: mlx | m | pdf | html
    • Two dimensional matrix for x and y, a third variable with color spectrum set via loop.
    • m: plot(2d, 2d) + jet + set(chart(m), 'Color', clr)

5.3 Write and Read Plots

  1. Graph Generate EPS Postscript Figures: mlx | m | pdf | html
    • EPS vector graphics, avoid bitmap (jpg, png), use vector graphics.
    • m: figure('Renderer', 'Painters')

6 Tables

6.1 Basic Table Generation

  1. Named Tables with Random Data: mlx | m | pdf | html
    • Convert a random matrix to a table with column and row names defined with arrays.
    • m: array2table() + strcat() + addvars() + matlab.lang.makeValidName()
  2. Order, Sort and Rename Columns: mlx | m | pdf | html
    • Convert a matrix to table with mean and sd columns. Rearrange and rename columns.
    • m: array2table() + rng() + addvars() + movevars() + removevars() + matlab.lang.makeValidName() + tb.Properties.VariableNames + tb.Properties.RowNames
  3. Array Based Row and Column Names: mlx | m | pdf | html
    • Generate a column and row named table. Convert row names to a column as strings. Remove Row Names.
    • m: array2table() + string() + strcat('rowA=', string((1:size(mt, 1)))) + tb_test_a.Properties.VariableNames + tb_test_a.Properties.RowNames + addvars(tb, rownames, 'Before', 1)
  4. Select Subset of Rows and Columns: mlx | m | pdf | html
    • Conditional selection based on cell values and column and row names.
    • m: tb(strcmp(tb.v1, "b"),:) + tb(tb.va==0.4,:)

6.2 Table Joining

  1. Stack Matlab Tables: mlx | m | pdf | html
    • Append columns to existing table. Stack tables vertically and horizontally.
    • Simulate a model, column combine simulation parameters with multi-row simulation results. Then row stack results from multiple simulations together.
    • m: array2table() + [tb_a tb_b] + [tb_a; tb_b] + tb.Properties.VariableNames + tb.Properties.RowNames

Please contact for issues or problems.

DOI

RepoSize CodeSize Language Release License

m4econ's People

Contributors

fanwangecon avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.