Selecting a specific part in a string array

1 回表示 (過去 30 日間)
Cem Eren Aslan
Cem Eren Aslan 2021 年 12 月 31 日
回答済み: Image Analyst 2021 年 12 月 31 日
Hello everone,
I want to wrtie a function that will separate first and last names at the input data. Input data is 30x1 cell array. It contains name and surname information. I try "split" function but some people has 2 or more names, so matlab gives size error. How can i fix it? My function as follows:
function seperation
strg = a1(:,1);
strg_cell=table2cell(strg);
i=1;
while i<31
x3(i,:)=split(strg_cell(i,1),' ');
i=i+1;
end
end

採用された回答

Image Analyst
Image Analyst 2021 年 12 月 31 日
@Cem Eren Aslan, try this. It will also work if there are 4 or more words in the person's name.
inputCellArray = {'Cem Eren Aslan', 'Steven MVP', 'ImageAnalyst'};
numCells = length(inputCellArray);
namesCellArray = cell(numCells, 3);
for k = 1 : length(inputCellArray)
thisCellContents = inputCellArray{k};
words = strsplit(thisCellContents);
for w = 1 : length(words)
namesCellArray{k, w} = words{w};
end
end
namesCellArray
namesCellArray = 3×3 cell array
{'Cem' } {'eren' } {'Aslan' } {'Steven' } {'MVP' } {0×0 double} {'ImageAnalyst'} {0×0 double} {0×0 double}

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 12 月 31 日
tmp = split(strg_cell(i,1));
x3(i,:) = tmp([1,end]);
The MATLAB approach would be to use a simple FOR loop, rather than painfully incrementing in a WHILE loop as if this was C++.

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by