![](/img/trans.png)
[英]sprintf error in MATLAB when trying to save cell array with strings and numbers
[英]MATLAB regexprep command with cell array of strings and numbers
我有一個包含字符串和數字的單元格數組。 字符串包含雙引號,這在MATLAB中給我帶來了麻煩。 我在此鏈接中找到了一種將單引號替換為雙引號的解決方案。 但是,該解決方案僅在所有單元格內容均為字符串且我的某些數字中包含數字時才起作用。 我不想將數字轉換為字符串,因為稍后將在工作流程中使用它們進行計算。
這是我擁有的單元格類型的示例以及到目前為止我嘗試過的示例:
myCell1 = {'';'"some words"';64;23;'"words"'};
myCell2={'';'more words';'more stuff';46;15};
Cell={myCell1, myCell2}
% Attempt at a for loop to only apply regexprep to strings
for i = 1 : numel(Cell)
for r = 1:numel(Cell{i})
if ischar(Cell{i}{r})
newCell{i}{r} = regexprep(Cell, '^"|"$', '');
end
end
end
非常感謝您弄清楚如何在此混合設置中將regexprep()應用於字符串。
在我看來,您快要擁有了。 我已經對您的代碼進行了一些修改,它似乎可以正常工作。 更改的行是那些帶有注釋的行。
for i = 1 : numel(Cell)
for r = 1:numel(Cell{i})
if ischar(Cell{i}{r})
newCell{i}{r} = regexprep(Cell{i}{r}, '^"|"$', ''); %// changed "Data" to "Cell"
else %// added this branch...
newCell{i}{r} = Cell{i}{r}; %// ... to keep cells containing numbers unchanged
end
end
end
處理正則表達式時,您別無選擇。 如果要將數字用於正則表達式,則必須將數字轉換為字符串。 但是,Luis Mendo的方法更簡單,因為在邏輯分支中只需要另一個if
語句即可。 該方法也很好,並且更簡單。
如果您不想這樣做並且想在正則表達式中使用數字,我們可以跟蹤單元格數組中哪些元素以數字開頭,將這些數字轉換為字符串,使用regexprep
,然后將這些條目轉換回完成后的數字。
您可以使用cellfun
來檢查單元格數組中的哪些元素是數字。 然后,將這些元素轉換為字符串,進行處理,然后再轉換回去。 首先檢查每個元素是否為isnumeric
的數字。 之后,您可以使用num2str
將數字轉換為字符串。 之后,使用str2num
將字符串轉換回數字。 換句話說,執行以下操作:
myCell1 = {'';'"some words"';64;23;'"words"'};
myCell2={'';'more words';'more stuff';46;15};
Cell={myCell1, myCell2};
newCellArray = cell(1,numel(Cell)); %// Place output cell array here
for i = 1 : numel(Cell)
%// Extract i'th cell
cel = Cell{i};
%// Which ones are numbers?
whichAreNumbers = cellfun(@isnumeric, cel);
%// Convert those numbers into strings
outStrings = cellfun(@num2str, cel(whichAreNumbers), 'uni', false);
%// Assign back into cell
cel(whichAreNumbers) = outStrings;
%// Apply regexprep now
newCell = regexprep(cel, '^"|"$', '');
%// Convert the numbers back
outVals = cellfun(@str2num, newCell(whichAreNumbers), 'uni', false);
newCell(whichAreNumbers) = outVals;
%// Place in master output cell array
newCellArray{i} = newCell;
end
此時的輸出為:
>> celldisp(newCellArray)
newCellArray{1}{1} =
''
newCellArray{1}{2} =
some words
newCellArray{1}{3} =
64
newCellArray{1}{4} =
23
newCellArray{1}{5} =
words
newCellArray{2}{1} =
''
newCellArray{2}{2} =
more words
newCellArray{2}{3} =
more stuff
newCellArray{2}{4} =
46
newCellArray{2}{5} =
15
如您所見,數字仍然保留,但每個字符串的引號均被刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.