how can convert string to matrix?

조회 수: 4 (최근 30일)
hesam gharaei
hesam gharaei 2018년 10월 27일
답변: Image Analyst 2018년 10월 27일
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
hesam gharaei
hesam gharaei 2018년 10월 27일
'abcb' is not separate.i need matrix with 1000 row and 4 column.
Stephen23
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개)

madhan ravi
madhan ravi 2018년 10월 27일
편집: madhan ravi 2018년 10월 27일
str2sym(U) %at the end
  댓글 수: 1
madhan ravi
madhan ravi 2018년 10월 27일
make sure you have symbolic toolbox

댓글을 달려면 로그인하십시오.


Stephen23
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);

Image Analyst
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)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by