Go to the MLX, M, PDF, or HTML version of this file. Go back to fan’s MEconTools Package, Matlab Code Examples Repository (bookdown site), or Math for Econ with Matlab Repository (bookdown site).
a = [1,2,3,4,5,6]';
b = reshape(a, [3,2])
b = 3x2
1 4
2 5
3 6
b(:)
ans = 6x1
1
2
3
4
5
6
a = [1,2,3;4,5,6;7,8,9;10,11,12]'
a = 3x4
1 4 7 10
2 5 8 11
3 6 9 12
b = reshape(a, [6,2])
b = 6x2
1 7
2 8
3 9
4 10
5 11
6 12
a = [1,2;3,4];
a_stacked = [a;a;a];
disp(a_stacked);
1 2
3 4
1 2
3 4
1 2
3 4
There is a 2 by 3 matrix, to be repeated 4 times, downwards. This is useful for replicating data matrix for say counterfactual purposes.
Below, we have two ways of repeating a matrix downwards. Copy as whole, or copy row by row.
row_count = 2;
col_count = 3;
repeat_mat_count = 2;
data_vec = 1:(row_count*col_count);
searchMatrix = reshape(data_vec,row_count,col_count);
% To repeat matrix downwards
rep_rows_idx = [1:row_count]'*ones(1,repeat_mat_count);
rep_rows_idx = rep_rows_idx(:);
rep_cols_idx = [1:col_count];
rep_cols_idx = rep_cols_idx(:);
searchMatrixRep_stack = searchMatrix(rep_rows_idx, rep_cols_idx);
% To insert repeated rows following original rows
rep_rows_idx = ([1:row_count]'*ones(1,repeat_mat_count))';
rep_rows_idx = rep_rows_idx(:);
searchMatrixRep_dup = searchMatrix(rep_rows_idx, rep_cols_idx);
disp(searchMatrix)
1 3 5
2 4 6
disp(searchMatrixRep_stack)
1 3 5
2 4 6
1 3 5
2 4 6
disp(searchMatrixRep_dup)
1 3 5
1 3 5
2 4 6
2 4 6
it_inner_fin = 5; it_outter_fin = 3;
it_inner_cur = it_outter_fin it_outter_cur = it_inner_fin
ar_it_cols_idx = 1:1:(it_inner_fin*it_outter_fin) ar_it_cols_inner_dim = repmat(1:it_inner_cur, \[it_outter_cur, 1\]) ar_it_cols_inner_dim(:)’
mt_it_cols_idx = reshape(ar_it_cols_idx, \[it_inner_cur, it_outter_cur\])’ mt_it_cols_idx(:)’
it_inner_fin = 5;
it_outter_fin = 3;
ar_it_cols_idx = 1:1:(it_inner_fin*it_outter_fin)
ar_it_cols_idx = 1x15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
mt_it_cols_idx = reshape(ar_it_cols_idx, [it_outter_fin, it_inner_fin])'
mt_it_cols_idx = 5x3
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
mt_it_cols_idx(:)'
ans = 1x15
1 4 7 10 13 2 5 8 11 14 3 6 9 12 15