MATLAB: Replacing elements of a matrix with vectors

matrix

I have a matrix of integers, for instance:
[1 2; 3 4], and I would like to replace each integer with a, for instance:
1 by [1 2 1], 2 by [2 7 2], 3 by [6 4 3], 4 by [9 8 2], so that the final matrix is:
[1 2 1 2 7 2; 6 4 3 9 8 2]
Any suggestions for how to do this?

Best Answer

Simply put the replacement arrays inside a cell array and then use the starting matrix as indices:
>> mat = [1,2;3,4];
>> rep = {[1,2,1],[2,7,2],[6,4,3],[9,8,2]};
>> cell2mat(rep(mat))
ans =
1 2 1 2 7 2
6 4 3 9 8 2