Fill cell in second column based on first column cell array
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 17 Aug 2017
Edited: Stephen23
on 17 Aug 2017
>> 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));
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!