Home > database >  How to convert a char array of lines of numbers including '↵' to integers in matlab?
How to convert a char array of lines of numbers including '↵' to integers in matlab?

Time:02-24

I have variable 'txt' of the type char and I want to turn it into an array of integers:

txt = '-1 1 -3 -1↵ -7 -4 -2 -3 -1 -2↵ -2 -24 -3 -1 -2 -2 -1 -1↵ -3 -1 0 -1 -2 -3 -4 -5↵ -5 -2 -1 -1 -2 -11-15-27↵ -5 -7 -30-19-16-18-19-18↵ -5 -4 -28-28-19-13↵ -4 -3 -13 -6

 '

size(txt)

ans =

 1   160

num2str(txt)

ans =

'-1 1 -3 -1
 -7 -4 -2 -3 -1 -2
 -2 -24 -3 -1 -2 -2 -1 -1
 -3 -1 0 -1 -2 -3 -4 -5
 -5 -2 -1 -1 -2 -11-15-27
 -5 -7 -30-19-16-18-19-18
 -5 -4 -28-28-19-13
 -4 -3 -13 -6
 
 '

str2num(txt)

ans =

 []

double(txt) also return an array of numbers but they are not the same as the number in the txt array. How can I turn txt array into integers?

CodePudding user response:

You have to find and eliminte the 'newline' charachters in your code first. the ASCII code for the newline is 10. So, try to use this code to find, eliminate them and replace them with space.

arr= #read the text;
arr(double(arr)==10) = ' ';
a = find(arr=='-')-1;
a = a(a>0);
indcs = a(find(arr(a) ~= ' '));
for i=1:length(indcs)
    arr = [arr(1:indcs(i)), ' ', arr(indcs(i) 1:end)];
    indcs = indcs 1;
end

x = str2num(arr)
  • Related