get rid of empty spaces in cells containing strings

4 views (last 30 days)
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 Comment
Image Analyst
Image Analyst on 6 May 2016
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?

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 6 May 2016
str={'103';'114';' 25';' 9';' 13';' 8';' 12';' 26'}
out=strtrim(str)

More Answers (3)

the cyclist
the cyclist on 5 May 2016
Here's one way:
cell_sample = regexprep(cell_sample,' ','')

James Tursa
James Tursa on 5 May 2016
Edited: James Tursa on 5 May 2016
Another (slower) way:
cell_sample = cellfun(@(x)x(x~=' '),cell_sample,'Uni',false)

John BG
John BG on 6 May 2016
Edited: John BG on 6 May 2016
Use
str2num
It trims any head tail blank space while at the same time converting fields to type double

Categories

Find more on Data Type Conversion 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!