how can convert string to matrix?
12 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-10-27
编辑:Stephen23
2018-10-27
"'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?).
回答(3 个)
Stephen23
2018-10-27
编辑:Stephen23
2018-10-27
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);
0 个评论
Image Analyst
2018-10-27
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)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!