Eliminate string from vector
4 views (last 30 days)
Show older comments
Giacomo Abrardo
on 18 Jun 2021
Commented: Giacomo Abrardo
on 19 Jun 2021
Hi, i created a vector containing 963 nc file. The problem is that some of them are the same but from two different version and i want to delete the previous version. For example, how can i eliminate row 844, 846 and 848 from my vector? Thanks all
0 Comments
Accepted Answer
Image Analyst
on 19 Jun 2021
You say "For example from c_gls to S1CSAR" so basically up until the last underline. Don't include _V and anything after that. This will do it:
% Create sample data
ca = {...
'c_gls_SSM1km_202007310000_CEURO_S1CSAR_V1.1.1.NC';...
'c_gls_SSM1km_202007310000_CEURO_S1CSAR_V1.1.2.NC';...
'c_gls_SSM1km_202008040000_CEURO_S1CSAR_V1.1.1.NC';...
'c_gls_SSM1km_202008040000_CEURO_S1CSAR_V1.1.2.NC';...
'c_gls_SSM1km_202008050000_CEURO_S1CSAR_V1.1.1.NC';...
'c_gls_SSM1km_202008050000_CEURO_S1CSAR_V1.1.2.NC'}
% Loop over each cell replacing it with the contents
% but only until the last underline.
for k = 1 : length(ca)
underlineIndexes = find(ca{k} == '_');
% Take up until the last underline
ca{k} = ca{k}(1:underlineIndexes(end) - 1);
end
ca = unique(ca) % Get unique and show results in command window.
You get
ca =
3×1 cell array
{'c_gls_SSM1km_202007310000_CEURO_S1CSAR'}
{'c_gls_SSM1km_202008040000_CEURO_S1CSAR'}
{'c_gls_SSM1km_202008050000_CEURO_S1CSAR'}
Is that what you want?
If you know that the last underline is always in the same location, you could simplify it to be
for k = 1 : length(ca)
ca{k} = ca{k}(1:38); % Extract the first 38 characters of the kth cell.
end
OK, 3 lines instead of 1 for the regexp() way, but you might find this more intuitive and less cryptic.
More Answers (1)
Image Analyst
on 18 Jun 2021
Did you try the unique() function? It has lots of options so be sure you understand which options to use.
If you need more help, attach your cell array in a .mat file with the paperclip icon.
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!