Appending strings to array
이전 댓글 표시
I would like to append a each word character of my string to an array, using the following code:
clear all
str = 'abc';
l = zeros(1,length(str)); % defining my empty list
for k = 1:length(str) % looping over the length of the string
l(k) = str(k);
end
The output I get for my list l however looks as like:
l =
97 98 99
I know that it is possible to get the individual string characters using l = num2str(str). However, I still can't figure out why this doesn't work.
댓글 수: 1
"I know that it is possible to get the individual string characters using l = num2str(str)"
To be honest, I don't see how this operation (which does absolutely nothing at all) is useful for you:
str = 'abc';
out = num2str(str)
It returns exactly the same character vector. If you want to "get the individual" characters (whatever that means) then you can do that just as well with the original (completely identical) character vector.
채택된 답변
추가 답변 (1개)
"l = zeros(1,length(str)); % defining my empty list "
That is not an "empty list":
- MATLAB does not have a "list" type.
- It is not empty.
- It is actually a numeric array with size 1x3, filled with zeros.
When you allocate characters to a numeric array MATLAB simply allocates the character code to the array. Note that MATLAB arrays are homogenous, that is their elements must be all of the same class. This means you cannot store characters with type char in a numeric array: all elements of a numeric array are numeric.
If you want to store different classes of data in one array (e.g. numeric and char) then you will need to use some kind of container array (e.g. a cell array, a structure, a table, etc.).
If you want to store characters in an array, then of course you can use a character array, e.g.:
str = 'abc';
out = repmat(' ',size(str));
for k = 1:numel(str)
out(k) = str(k);
end
out
Or the MATLAB approach:
out = str
카테고리
도움말 센터 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!