Fill cell in second column based on first column cell array

6 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Stephen23
Stephen23 el 17 de Ag. de 2017
Editada: Stephen23 el 17 de Ag. de 2017
Method one: regexp and convert using subtraction:
>> 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
Method two: regexprep:
>> 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));
  1 comentario
Lauryn Burleigh
Lauryn Burleigh el 17 de Ag. de 2017
This is definitely easier than what I was trying to do. Thank you so much!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by