Fill cell in second column based on first column cell array
6 次查看(过去 30 天)
显示 更早的评论
I have a cell array of image names in the first column ('9_X_0_a.bmp', '9_X_0_b.bmp','19_X_0_a.bmp', '19_X_0_b.bmp', etc.). I would like to fill the second column with either '1' or '2' based on if the image names contain 'a' or 'b'.
I currently have the code set to run as an 'if' statement which works but only for one index. In other words, it will place the proper number in the second column for either 'a' or 'b' images, but not for both. Any advice?
for i = length(listOfFiles1);
indexa = find(contains(listOfFiles1, 'a'));
indexb = find(contains(listOfFiles1, 'b.bmp'));
if i == indexa
listOfFiles1{indexa,2} = 1;
elseif i == indexb
listOfFiles1{indexb,2} = 2;
end
end
0 个评论
采纳的回答
Stephen23
2017-8-17
编辑:Stephen23
2017-8-17
>> C = {'9_X_0_a.bmp';'9_X_0_b.bmp';'19_X_0_a.bmp';'19_X_0_b.bmp'};
>> D = regexp(C,'[ab](?=\.bmp)','match','once');
>> C(:,2) = num2cell([D{:}]-'a'+1)
C =
'9_X_0_a.bmp' 1
'9_X_0_b.bmp' 2
'19_X_0_a.bmp' 1
'19_X_0_b.bmp' 2
>> C = {'9_X_0_a.bmp';'9_X_0_b.bmp';'19_X_0_a.bmp';'19_X_0_b.bmp'};
>> C(:,2) = regexprep(C,{'.*a\.bmp$','.*b\.bmp'},{'1','2'}) % as string
C =
'9_X_0_a.bmp' '1'
'9_X_0_b.bmp' '2'
'19_X_0_a.bmp' '1'
'19_X_0_b.bmp' '2'
or as double:
D = regexprep(C,{'.*a\.bmp$','.*b\.bmp'},{'1','2'});
C(:,2) = num2cell(str2double(D));
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!