Reputation: 975
I have imported some information from Excel, that's both strings and numbers. I read the Excel-file in MATLAB in raw format
Now, I have a column in a big matrix as
[1]
'1A'
[2]
[3]
[4]
[505]
[601]
[7]
[8]
this is how the xlsread
command gave it to me. I want to convert all these into strings like
['1' , '1A', '2' and so on..]
.
I am struggling to do it. I want no blank spaces in each element. I mean it should not be like [ ' 1', ' 1A', ' 2' and so on]....
Upvotes: 1
Views: 447
Reputation: 14939
Try to combine cellfun
and num2str
like this:
A = {1, '1A', 2, 3, 4, 505, 601, 7, 8}'
str = cellfun(@(c) num2str(c), A, 'UniformOutput', false).'
str =
'1' '1A' '2' '3' '4' '505' '601' '7' '8'
You can use num2str
on stings, so you do not have to check if variable is a string or a numeric value. Note that the spaces in the result are between the elements, and not in the elements itself. So,
str(1)
ans =
'1'
str(2)
ans =
'1A'
If your input data may contain spaces (your sample didn't), you can eliminate those by using an additional cellfun
like this:
cellfun(@(c) c(c~=' '), str, 'UniformOutput', false)
Side note: In most MATLAB functions, you can shorten parameter names, such as UniformOutput, false
. This can be un, 0
, uni, 0
... etc, as long as the letters represent a unique parameter and can't mean something else. This is a nice trick if you write it in the command window, but I would avoid it in real code, as it could possibly break the code if The MathWorks determines to create a parameter called unit
, UniformInput
or something else starting with uni
. Just a little tip =)
Upvotes: 1
Reputation: 789
There is a variety of ways to do this. I'm assuming the matrix you refer to is a cell array? Meaning it can contain both numbers and strings?
If so, you can loop through each cell element and use isa() to determine the object type in each element, then convert to a string accordingly (i.e. num2str()).
If you run into trouble with white spaces, look into using the family of functions related to regexpr() in matlab, they can identify certain characters and perform operations like deleting them from a string of char.
Upvotes: 0