get rid of empty spaces in cells containing strings

Hi everyone,
I have created a cell 62x1, cell_sample, which reads like this:
'103'
'114'
' 25'
' 9'
' 13'
' 8'
' 12'
' 26'
and so on.. till the last cell. The problem is that it always has 3 characters, so for a one digit number I am getting 2 spaces and the number, for a two digit number I'm getting one space and the number, etc. I want to remove the spaces to get sth like this:
'103'
'114'
'25'
'9'
'13'
'8'
'12'
'26'
The data is read from an excel sheet, piece of code:
sample=xlsread('screws.xlsx',1,'H2:H63')
Num_sample=num2str(sample)
cell_sample = cellstr(Num_sample)

1 Commento

I like Azzi's answer best, but why are you converting it to strings? Wouldn't leaving the numbers as numbers be easier to use after that in your code? Why make it harder on yourself?

Accedi per commentare.

 Risposta accettata

str={'103';'114';' 25';' 9';' 13';' 8';' 12';' 26'}
out=strtrim(str)

Più risposte (3)

James Tursa
James Tursa il 5 Mag 2016
Modificato: James Tursa il 5 Mag 2016
Another (slower) way:
cell_sample = cellfun(@(x)x(x~=' '),cell_sample,'Uni',false)
John BG
John BG il 6 Mag 2016
Modificato: John BG il 6 Mag 2016
Use
str2num
It trims any head tail blank space while at the same time converting fields to type double

Categorie

Scopri di più su MATLAB in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by