如何将包含'↵'的数字行的字符数组转换为matlab中的整数?

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

我有一个 char 类型的变量 'txt',我想把它变成一个整数数组:

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)

答案=

 1   160

num2str(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
 
 '

str2num(txt)

答案=

 []

double(txt) 也是 return 一个数字数组,但它们与 txt 数组中的数字不同。 如何将 txt 数组转换为整数?

您必须首先找到并消除代码中的 'newline' 个字符。换行符的 ASCII 码是 10。因此,尝试使用此代码查找、消除它们并替换为 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)