Skip to content

Latest commit

 

History

History
177 lines (142 loc) · 24.5 KB

README_OLD.md

File metadata and controls

177 lines (142 loc) · 24.5 KB

HitCount Star Fork Star

This is a work-in-progress website of support files for using matlab, produced by Fan. Materials gathered from various projects in which matlab codes are used. Matlab files are linked below by section with livescript files. Tested with Matlab 2019a.

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

Please contact FanWangEcon for issues or problems.

1. Arrays, Cells and Maps

1.1 Numeric Array Manipulations

  1. Accumarray Examples: m | mlx | pdf | html
    • accumarray to sum up probabilities/values for discrete elements of arrays
    • m: unique, reshape, accumarray
  2. Array Broadcasting Examples: m | mlx | pdf | html
    • broadcast means: array + array' + matrix = matrix
  3. Array Random Draws and Permutation: m | mlx | pdf | html
    • draw randomly from array, permutate arrays
    • m: ndgrid, cell2mat(cellfun(@(m) m(:), cl_mt_all, 'uni', 0))
  4. Imaginary Elements of Array: m | mlx | pdf | html
    • find imaginary elements of array
    • m: imag
  5. Array Reshape, Repeat and Expand: m | mlx | pdf | html
    • reshape and flatten arrays
    • m: reshape
  6. Array Index Slicing and Subsetting to Replace and Expand: m | mlx | pdf | html
    • index based column and row expansions
    • anonymous function to slice array subsets
    • m: sub2ind; f_subset = @(it_subset_n, it_ar_n) unique(round(((0:1:(it_subset_n-1))/(it_subset_n-1)) times (it_ar_n-1)+1));
  7. Grid States, Choices and Optimal Choices Example: m | mlx | pdf | html
    • states, choices, and find max

1.2 Cell Array Manipulations

  1. List Comprehension with Cells: m | mlx | 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, cell2mat(cellfun(@(m) find(strcmp(ls_st_param_key, m)), cl_st_param_keys, 'UniformOutput', false))
  2. Permutate Cells: m | mlx | 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: m | mlx | pdf | html
    • combine string cell arrays and string
    • m: [{st_param}, ls_st_param_key, cl_st_param_keys]
  4. Cells Nested in Cells: m | mlx | pdf | html
    • Cell of cells with inner cell having multiple types
    • m: 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.3 String Array Manipulations

  1. String Basics: m | mlx | pdf | html
    • cut string suffix and append new suffix
    • m: str_sub = split(string, "."); str_sub = strcat(str_sub{1}, '_m.m')
  2. String Arrays: m | mlx | pdf | html
    • concatenate string arrays, string with string,
    • string with numeric arrays, numeric arrays together as strings, combine numeric arrays and append string
    • find string in string cell array
    • print display numerics as strings
    • m: repmat, num2str, strcat, strjoin, fprintf, strcmp, strrep, cel2mat(cellfun(@(m) find(strcmp())))
  3. String Concatenations: m | mlx | pdf | html
    • concatenate multiple numeric arrays together with strings and format
    • m: cellstr, strcat

1.4 Container Map Management

  1. List Comprehension with Cells: m | mlx | pdf | html
    • numeric container map
    • dynamically filled container map
    • m: isKey, containers.Map('KeyType', 'char', 'ValueType','any'), strjoin
  2. Print Container Map Keys and Values: m | mlx | pdf | html
    • loop over map, display keys and values
    • m: strjoin, keys(map), values(map)
  3. Container Map Varied Value Types: m | mlx | pdf | html
    • numeric scalar, string, matrix as values for map container
    • get values for multiple keys in map
    • m: map.keys, map.values, params_group = values(param_map, {'share_unbanked_j', 'equi_r_j'})
  4. Cell Override: m | mlx | 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. Matlab Programming Practices

2.1 Default Parameters

Default parameters allow for maintaining code testability. The varargin structure could lead to excessive code lines. Container Map works well.

  1. Multi-type Varargin Structure
    • use for functions with limited parameters
    • m: function [out_put] = func_name(varargin), cell2mat
  2. Container Map Structure: ipynb | mlx | m | html | pdf
    • core model functions with potentially many parameters, preferred
    • m: 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. Graphs and Tables

3.1 Basics

  1. Save Images as EPS: m | mlx | pdf | html
    • eps graphs are essential for clear images in pdf
    • eps = vector graphics, avoid bitmap (jpg, png), use vector graphics
    • m: figure('Renderer', 'Painters')
  2. Image Pick Colors: m | mlx | pdf | html
    • display safe colors
    • m: blue = [57 106 177]./255, fill(x, y, cl_colors{it_color});
  3. Figure Titling and Legend: m | mlx | 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');
  4. Graph Many Lines Legend for Subset: m | mlx | 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: clr = jet(numel(chart)), set(chart(m),'Color',clr(m,:)); legend2plot = fliplr([1 round(numel(chart)/3) round((2numel(chart))/4) numel(chart)]);*

3.2 Graph Examples

  1. Scatter Plot: m | mlx | pdf | html
    • scatter multiple lines different colors, shapes and sizes
    • m: scatter, Marker, MarkerEdgeColor, MarkerEdgeAlpha, MarkerFaceColor, MarkerFaceAlpha; scatter(x, y, size)
  2. Line + Line Plot: m | mlx | pdf | html
    • scatter and lines multiple lines different colors, shapes and sizes
    • m: xline(0), yline(0), refline([1 0]); plot(x,y), HandleVisibility, Color, LineStyle, LineWidth

3.3 Graph Programs

  1. 3 Var Line Color, 2D-X 2D-Y and 1D-Color: ipynb | mlx | m | html | pdf
    • 2d matrix for x and y, column vector value for color spectrum
    • m: plot(2d, 2d) + jet + set(chart(m), 'Color', clr)
  2. Z(X,Y): Z = y-axis, X = x-axis, Y = color: m | html | pdf
    • 3 dimensional graph on 2D with, scatter and line joint
    • m: scatter + plot + (HandleVisibility, linspecer Color)

3.4 Tables

  1. Add Columns to Table: ipynb | mlx | M | html | pdf
    • call: ff_mat2tab(mt_data, ar_st_colnames)
    • core: array2table, table.Properties.VariableNames
  2. Export Table or Mat: ipynb | mlx | M | html | pdf
    • call: ff_sup_save_prep(st_path_folder, st_file_name, bl_exp_csv, mt_data, ar_st_colnames); dependency: ff_mat2tab
    • core: mkdir, csvwrite, save

4 Speed Improvements

4.1 Interpolation

  1. Rational Exponent: Interpolation over Utility of Consumption: u(c) where u evaluation involves rational exponentiation, pre-calculate and interpolate
    • Interpolate function testing: ipynb | html
    • Interpolate function (griddedInterpolant): m | html
    • Direct evaluation and interpolate speed comparison: m | ipynb | html
      • core: interp1, griddedInterpolant, nearest vs linear vs spline

4.2 Matrix and Index

  1. Cell Array Store u(c) to Avoid Duplicate Computation over Iteration: u(c) across iterations often shares many common values
    • Cell matrix part update function testing: ipynb | html
    • Cell matrix part update function: m | html
    • Methods for matrix updating speed comparisons: m | ipynb | html
      • core: cell{}, cl_u_store{i}(ar_it_update,:) = f_u(f_c(ar_coh, ar_kp(ar_it_update), ar_bp(ar_it_update)));
  2. Matrix Index Value Replace: Negative Consumption Utility: ipynb | mlx | m | html | pdf

Please contact for issues or problems.

RepoSize CodeSize Language Release License