設C
是要分配給號碼A
字母排列。然後
A = [1 3 5];
B = {[1]; [3]; [5]; [1;3]; [1;5]; [3;5]; [1;3;5]};
C = ['a', 'b', 'c']
k = 6; % indicates current line of B
str = ['you can have ' strrep(strrep(sprintf('_%c_', ...
C(ismember(A, B{k}))'), '__', ' or '), '_', '')];
結果
str =
you can have a or b or c
如果你想創建到所有領域的答覆中B
一次,您可以使用
allStr = arrayfun(@(x) ['you can have ' strrep(strrep(sprintf('_%c_', ...
C(ismember(A, B{x}))'), '__', ' or '), '_', '')], ...
(1:length(B))', 'uniformoutput', false)
這導致
allStr =
'you can have a'
'you can have b'
'you can have c'
'you can have a or b'
'you can have a or c'
'you can have b or c'
'you can have a or b or c'
一步這段代碼的一步解釋如下:
% which contents of A can be found in B?
idx = ismember(A, B{k})';
% to which letters do these indices correspond?
letters = C(idx);
% group the letters in a string embedded in '_' as place holders for later use
% by this, the places between letters will be marked with '__' and the places
% at the beginning and the end of the string will be marked with '_'
stringRaw = sprintf('_%c_', letters);
% replace each occurrence of '__' by ' or '
stringOr = strrep(stringRaw, '__', ' or ');
% replace each occurrence of '_' by ''
stringClean = strrep(stringOr, '_', '');
% add first half of sentence
stringComplete = ['you can have ' stringClean];
要獲得完整的單詞(如在意見中的要求),您需要轉換C
進入細胞這個工作字符串數組,並更新相應的下式:
A = [1 3 5];
B = {[1]; [3]; [5]; [1;3]; [1;5]; [3;5]; [1;3;5]};
C = {'first', 'second', 'third'}
k = 7; % indicates current line of B
str = ['you can have ' strrep(strrep(sprintf('_%s_', ...
C{ismember(A, B{k})}), '__', ' or '), '_', '')];
這導致:
str =
you can have first or second or third
你能解釋一下你的代碼嗎?我真的不明白髮生了什麼,並且很想知道它是如何工作的。 – NLed 2013-03-06 11:10:54
@NLed請參閱我的更新回答。 – 2013-03-06 13:08:37
謝謝,讓我更有意義..'arrayfun(@x ..)'代表什麼? '@ x'有什麼用?對於第二個代碼,最後一部分,你有'(1:length(B))','uniformoutput',false)'......這是什麼意思? – NLed 2013-03-06 20:52:51