how can convert string to matrix?

2 views (last 30 days)
hesam gharaei
hesam gharaei on 27 Oct 2018
Answered: Image Analyst on 27 Oct 2018
i have 'abcb' in output but i want a b c b in output.i need matrix in output.
if true
clc;
clear all;
u=randi(3,1000,4);
for j=1:4
for i=1:1000
if u(i,j)==1
U(i,j)='a';
elseif u(i,j)==2
U(i,j)='b';
else
U(i,j)='c';
end
end
end
end
  3 Comments
hesam gharaei
hesam gharaei on 27 Oct 2018
'abcb' is not separate.i need matrix with 1000 row and 4 column.
Stephen23
Stephen23 on 27 Oct 2018
Edited: Stephen23 on 27 Oct 2018
"'abcb' is not separate"
The character vector 'abcb' consists four separate characters, which are easily accessible using indexing. Each character is one element of the char array, in exactly the same way that a numeric array has separate elements (e.g. four elements in this example):
[1,2,3,1]
It is not clear what you want, or what you expect to see. What you have shown is a character vector and requested that it should be a matrix (it is already), and that you want it to be "separate" (each character is a separate element of the character array). What you showed in your question "...i want a b c b in output" could be achieved by adding space characters into the character vector, or perhaps by using a cell array (but that would pointlessly complicate things). It is not clear how you think a character array should be like (other than simply containing the characters (which is what they do)), or why those spaces are so important (i.e. how are you going to process this data?).

Sign in to comment.

Answers (3)

madhan ravi
madhan ravi on 27 Oct 2018
Edited: madhan ravi on 27 Oct 2018
str2sym(U) %at the end

Stephen23
Stephen23 on 27 Oct 2018
Edited: Stephen23 on 27 Oct 2018
Get rid of the nested loops, they are not an effective use of MATLAB.
It is much simpler and more efficient to use basic indexing:
>> u = randi(3,1000,4);
>> v = 'abc';
>> m = v(u);
>> m(1:10,:) % take a look at the first ten rows
ans =
cccb
accc
ccba
babb
cbba
cbaa
bccc
bcbb
babc
cbbc
If you really want the characters "separate" then you could use a cell array:
>> c = num2cell(m);

Image Analyst
Image Analyst on 27 Oct 2018
Looks like you want to put a space between characters. To do that, try this:
% Demo to interleave spaces between letters in a string.
s = 'abcb' % A simple string as your input.
spaces = ones(length(s), 1) * ' '
s2 = reshape([s', spaces]', 1, []) % s2 now has spaces after the letters
% If you want to trim off any trailing space, use strtrim()
s2Trimmed = strtrim(s2)

Community Treasure Hunt

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

Start Hunting!