Populating cell array using lookup table

66 views Asked by At

I have a 2D matrix containing only integers. I also have a cell array tickerListthat contains names of equity tickers. The number of columns in matrixequals the number of elements in tickerList.

I am trying to create cellArrayNew by replacing the integers within matrix by its corresponding names in tickerList. So, for example, if matrix(1,1)=3and tickerList(3)='S&P 500', I would like to have cellArrayNew(1,1)='S&P 500'.

1

There are 1 answers

5
Rody Oldenhuis On BEST ANSWER

Just use the matrix as an index into tickerList:

% Sample column names
tickerList = {'Col1' 'Col2' 'Col3'};

% Example matrix   
N = numel(tickerList);
matrix = randi(N, [4, N]);

% The matrix is already in index form, so just index:
cellArrayNew = tickerList(matrix);

If the matrix contains indices that are somehow not in tickerList, use ismember:

% Make some elements 'NaN';
matrix(rand(size(matrix)) < 0.2) = NaN;

% Determine which elements are in tickerList, 
% as well as where they are precisely
[isin, I] = ismember(matrix, 1:N);

% Construct new matrix
cellArrayNew = repmat({NaN}, size(matrix)); % <- use any filler you want
cellArrayNew(isin) = tickerList(I(isin))

Result of my example:

cellArrayNew = 
    'Col2'    'Col1'    [ NaN]
    'Col3'    [ NaN]    'Col2'
    'Col3'    'Col3'    'Col3'
    'Col3'    'Col1'    'Col2'