splitting a char with no delimiter
Show older comments
Hi,
Does anyone know how to split a four character cell array string into 2(or better 4) separate strings? A= 'A5C9' %splitting into A1=A5 A2=C9
or even better something like A(1)=A A(2)= 5 A(3)= C A(4)= 9 so that I could use them to index a larger array?
For clarity this question was incorrectly posed, the problem was having a char within a cell, and needing to extract the char and index it. My bad for not realising the differences between strings and chars and should not have written {'...'}, much thanks to all who helped clarify.
Best regards
Steve
8 Comments
Rik
on 15 Jan 2018
A={'A5C9'};A=A{1};
This is already working like you describe, although the elements are all still chars, not normal values. Also, how were you planning on using letters to index things? Would you convert them with hex2dec?
Note:
A = 'A5C9' %no enclosing {}
could be called a string. Better would be to call it a char array as since R2016b there is also a string type.
A = {something}
is a cell array of something. Not the same thing at all.
A{1} = A5
is not even valid matlab syntax.
I point that out because your sloppy notation makes it very hard to understand what it is exactly you want. For example, the last part of your question does not make much sense. if
A = 'A5C9'
then A(1) is already 'A', A(2) is already '5', etc.:
>> A = 'A5C9';
>> A(1)
ans =
'A'
>> A(2)
ans =
'5'
Stephen Devlin
on 15 Jan 2018
Stephen Devlin
on 15 Jan 2018
Stephen Devlin
on 15 Jan 2018
Edited: Stephen Devlin
on 15 Jan 2018
"I am not sure why my cell, which tells me it is a string"
Because cell arrays can contain any other data types it actually tells us nothing about the class of its contents.
"I am not sure why my cell, which tells me it is a string, does not have the A(4)=9"
Because what you appear to have is a char vector in a cell array. And clearly it makes no sense to try to access the individual characters while it is still in the cell (so you need to use some cell indexing first). But this is all speculation, because so far you have told/shown us about four different explanations of what you have (title says char, text says string, example shows cell with char). It might be easiest for everyone if you simply uploaded the complete variable in a .mat file for us to look at.
Stephen Devlin
on 15 Jan 2018
Accepted Answer
More Answers (0)
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!