假设A
是输入单元阵列,这里可能有两种方法。
方法#1
%// Initlialize output array
Aout = cell(size(A));
for k = 1:size(A,2)
%// Select one column
Ak = A(:,k);
%// Logical array with size of Ak and ones at places with non-empty strings
pos = cellfun(@(x) ~isempty(x), Ak);
%// Find unique strings and find indices for all places in that column
%// with respect to those unique strings
[unq_str,~,str_idx] = unique(Ak,'stable');
%// Perform cumsum on pos to get an array with a "stepped" array that
%// steps up at each non-empty string position.
%// Then replace each stepping number with the string IDs
idx = changem(cumsum(pos),str_idx(pos),1:sum(pos));
%// Index into each column with those replaced IDs for the final output
Aout(:,k) = unq_str(idx);
end
与输入稍微改变了一下更加积极地测试出该解决方案的代码,我们不得不代码运行后 -
A =
'a' 'b'
'' ''
'' 'a'
'c' ''
'' 'd'
'a' ''
'' 'f'
'c' 'a'
Aout =
'a' 'b'
'a' 'b'
'a' 'a'
'c' 'a'
'c' 'd'
'a' 'd'
'a' 'f'
'c' 'a'
方法#2 [小巧,也许更高效]
您可以输入单元阵列重塑成一个单一的圆柱电池阵列,因此您将无法通过 单元阵列的列需要循环,这可能导致更高效和紧凑的代码 -
%// Reshape all cells into a single columned cell array
A1 = A(:);
%// Rest of the code borrowed from previous approach with reshaping added
%// at the end to bring the output back to the size of input array
pos = ~cellfun('isempty', A1);
[unq_str,~,str_idx] = unique(A1,'stable');
Aout = reshape(unq_str(changem(cumsum(pos),str_idx(pos),1:sum(pos))),size(A));
奖励:定制化实施的changem
前面列出的代码使用changem
需要Mapping Toolbox
。所以,如果你确实有这个问题,这里有一个定制的版本,用bsxfun
和max
实现,并且仅仅是早期解决方案代码here的抛光版本。这里去自定义函数代码 -
%// CHANGEM_CUSTOM Home-cooked vesion of CHANGEM with MAX, BSXFUN
function A = changem_custom(A,newvals,oldvals)
[valid,id] = max(bsxfun(@eq,A(:),oldvals(:).'),[],2); %//'
A(valid) = newvals(id(valid));
return;
因此,要使用这个自定义函数替换changem
,只是在前面的代码替换函数调用的名字在那里。
优秀。感谢您的解决方案。今天,我学习了新的功能“changem”。 – nik 2015-01-31 22:46:43
@nik是的!事实上,我之前只看到过一次,所以它对我来说也很新颖! – Divakar 2015-01-31 22:47:21
哇! 'changem'!凉!如果我想要替换矩阵中的多个条目,我总是使用逻辑索引来循环它。很高兴知道这里有一项便利功能。 +1 – rayryeng 2015-02-01 00:36:54