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.
- Accumarray Examples: m | mlx | pdf | html
- accumarray to sum up probabilities/values for discrete elements of arrays
- m: unique, reshape, accumarray
- Array Broadcasting Examples: m | mlx | pdf | html
- broadcast means: array + array' + matrix = matrix
- 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))
- Imaginary Elements of Array: m | mlx | pdf | html
- find imaginary elements of array
- m: imag
- Array Reshape, Repeat and Expand: m | mlx | pdf | html
- reshape and flatten arrays
- m: reshape
- 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));
- Grid States, Choices and Optimal Choices Example: m | mlx | pdf | html
- states, choices, and find max
- 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))
- 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))
- Combine Cells: m | mlx | pdf | html
- combine string cell arrays and string
- m: [{st_param}, ls_st_param_key, cl_st_param_keys]
- 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});
- 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')
- 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())))
- String Concatenations: m | mlx | pdf | html
- concatenate multiple numeric arrays together with strings and format
- m: cellstr, strcat
- List Comprehension with Cells: m | mlx | pdf | html
- numeric container map
- dynamically filled container map
- m: isKey, containers.Map('KeyType', 'char', 'ValueType','any'), strjoin
- Print Container Map Keys and Values: m | mlx | pdf | html
- loop over map, display keys and values
- m: strjoin, keys(map), values(map)
- 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'})
- 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]
Default parameters allow for maintaining code testability. The varargin structure could lead to excessive code lines. Container Map works well.
- Multi-type Varargin Structure
- use for functions with limited parameters
- m: function [out_put] = func_name(varargin), cell2mat
- 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]
- 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')
- Image Pick Colors: m | mlx | pdf | html
- display safe colors
- m: blue = [57 106 177]./255, fill(x, y, cl_colors{it_color});
- 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');
- 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)]);*
- 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)
- 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 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)
- 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)
- Add Columns to Table: ipynb | mlx | M | html | pdf
- call: ff_mat2tab(mt_data, ar_st_colnames)
- core: array2table, table.Properties.VariableNames
- 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
- Rational Exponent: Interpolation over Utility of Consumption: u(c) where u evaluation involves rational exponentiation, pre-calculate and interpolate
- Cell Array Store u(c) to Avoid Duplicate Computation over Iteration: u(c) across iterations often shares many common values
- Matrix Index Value Replace: Negative Consumption Utility: ipynb | mlx | m | html | pdf
- u(c) when c < 0, quickly replace matrix values by index
- functions: standard index replace, fast index replace
- interp1, griddedInterpolant, nearest vs linear vs spline