只需使用矩陣的一個索引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'
爲什麼你使用'ismember'。從你的解決方案中,我才知道'I'等於'矩陣'。所以,非常簡單的解決方案似乎是 'cellArrayNew = tickerList(matrix)' 我錯過了什麼嗎? – Andi
@安迪......非常真實。必須一直睡在那裏:) –
@Andi只是記住未來 - 「ismember」允許你對*可能*的元素做同樣的事情,超過'tickerList'的長度(情況I通常會遇到,這可能是爲什麼我的肌肉記憶在踢這個答案時踢了☺) –