Error in converting array in double to string

조회 수: 4 (최근 30일)
Arkaniva Sarkar
Arkaniva Sarkar 2021년 9월 7일
편집: Dave B 2021년 9월 10일
These errors occured when I tried to convert an array in double to string using the following methods.
Method 1:
str = [];
arr = [1,2,3,4,5];
for i=1:length(arr)
str(end+1) = num2str(arr(i));
end
disp(str)
49 50 51 52 53
Method 2:
arr = [1,2,3,4,5];
str = zeros(1,length(arr))
for i=1:length(arr)
str(i) = sprintf('%0.0f',arr(i));
end
disp(str)
49 50 51 52 53
I hoped to get something like [ '1', '2', '3', '4', '5' ] but the answers were these numbers (49,50,51,52,53) which I don't know from where they are coming from.
I tried using only num2str(arr(1)) or sprintf('%0.0f', arr(1)) to test whether they are giving correct answers, which to my suprise returned '1' as a string in both the cases. The error is occuring only while appending the string to the array.
Can anyone please provide an explaination for this?

채택된 답변

Dave B
Dave B 2021년 9월 7일
편집: Dave B 2021년 9월 7일
it's pretty confusing, but when you made str you made it as a double array.
str = [];
class(str)
ans = 'double'
So when you assign something to it it's getting cast to string.
You could've done this:
arr = [1,2,3,4,5];
str = '';
for i = 1:length(arr)
str(i)=num2str(arr(i));
end
str
str = '12345'
But it's kindof weird to have ['1' '2' '3' '4' '5'] as it just jumbles into one long char vector. Doing the whole thing at once might be better in some regards, this adds some whitespace so if you're going to use it as a title in a plot or a display in the command window you might be happy enough:
num2str(arr)
ans = '1 2 3 4 5'
Doing a cell array of character vectors (or cellstr) might be another approach:
str = cell(1,length(arr));
for i = 1:length(arr)
str{i} = num2str(arr(i));
end
str
str = 1×5 cell array
{'1'} {'2'} {'3'} {'4'} {'5'}
% note to index them, you'd do str{3} to get the third character vector
But your best bet (IMO) is to use string instead of char. Strings are much more natural, and you don't need a loop:
str = string(arr)
str = 1×5 string array
"1" "2" "3" "4" "5"
If you want the sprintf like controls, compose works well:
str = compose("%0.2f", arr)
str = 1×5 string array
"1.00" "2.00" "3.00" "4.00" "5.00"
  댓글 수: 2
Arkaniva Sarkar
Arkaniva Sarkar 2021년 9월 8일
Thank you for such a detailed answer.
Can you also help me understand how are 49 50 51 52 53 coming?
Dave B
Dave B 2021년 9월 10일
편집: Dave B 2021년 9월 10일
Ah yes, sorry I skipped this part. Every character has a numeric equivalent, not just in MATLAB. The standard that modern MATLAB uses is called UTF-16 which (as far as I understand) is the standard everywhere nowadays.
It's a bit counter-intuitive but the numeric equivalent to '1' isn't 1, the numbers start at 49. When MATLAB switches the chars to numeric you get the numeric codes for them.
With chars you can use double to switch to numeric representation and char to switch back:
double('12345')
ans = 1×5
49 50 51 52 53
char([49 50 51 52 53])
ans = '12345'
double('Dave')
ans = 1×4
68 97 118 101
char([68 97 118 101])
ans = 'Dave'
This is actually, occasionally, useful. For example, suppose you wanted to check if an input was a capital letter (note that there are more sophisticated approaches, but this is quick and easy):
testchars='ASDFxxW1;*0d';
testchars >= 'A' & testchars <= 'Z'
ans = 1×12 logical array
1 1 1 1 0 0 1 0 0 0 0 0
Note that in modern MATLAB these don't have to be 'plain old letters' but can be emojis as well:
abs('I ❤ MATLAB') % I often use abs instead of double, it works just as well and it's shorter!
ans = 1×10
73 32 10084 32 77 65 84 76 65 66
To make things really confusing, sometimes a single character can even go with two values (this is the 16 part of UTF-16)
char([hex2dec('D834') hex2dec('DD1E')])
ans = '𝄞'
Most of the time this numeric code stuff just gets in the way. String is a much more modern way of working with text and gave us an opportunity to rethink this pattern
double("12345")
ans = 12345
double(["1" "2" "3" "4" "5"])
ans = 1×5
1 2 3 4 5
double("Dave")
ans = NaN
string(12345)
ans = "12345"
string([1 2 3 4 5])
ans = 1×5 string array
"1" "2" "3" "4" "5"
You can read something a little more official: here.

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

추가 답변 (1개)

Malik Cheriaf
Malik Cheriaf 2021년 9월 7일
str=string(arr)
% result=[ "1" "2" "3" "4" "5"]

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by