使用查找表填充单元格数组

时间:2017-01-06 10:19:42

标签: matlab lookup-tables

我有一个仅包含整数的2D matrix。我还有一个包含股票代码名称的单元格数组tickerListmatrix中的列数等于tickerList中的元素数。

我正在尝试通过将cellArrayNew中的整数替换为matrix中的相应名称来创建tickerList。因此,例如,如果matrix(1,1)=3tickerList(3)='S&P 500',我希望cellArrayNew(1,1)='S&P 500'

1 个答案:

答案 0 :(得分:1)

只需使用矩阵作为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);

如果矩阵在tickerList中包含某些的索引,请使用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))

我的例子的结果:

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