Error in converting array in double to string
Show older comments
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?
Accepted Answer
More Answers (1)
Malik Cheriaf
on 7 Sep 2021
0 votes
str=string(arr)
% result=[ "1" "2" "3" "4" "5"]
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!