我有一个文本文件,其中包含以下列方式的二进制数据:
00000000000000000000000000000000001011111111111111111111111111111111111111111111111111111111110000000000000000000000000000000
00000000000000000000000000000000000000011111111111111111111111111111111111111111111111000111100000000000000000000000000000000
00000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111100000000000000000000000000000000
00000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000
00000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111100000000000000000000000000000000
00000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111100000000000000000000000000000000
00000000000000000000000000000000000000011111111111111111111111111111111111111111111111000111110000000000000000000000000000000
00000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111110000000000000000000000000000000
00000000000000000000000000000000000000000000111111111111111111111111111111111111110000000011100000000000000000000000000000000
00000000000000000000000000000000000000011111111111111111111111111111111111111111111111100111110000000000000000000000000000000
00000000000000000000000000000000000111111111111111111111111111111111111111111111111111110111110000000000000000000000000000000
00000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000
00000000000000000000000000000000000000001111111111111111111111111111111111111111111111000011100000000000000000000000000000000
00000000000000000000000000000000000000001111111111111111111111111111111111111111111111000011100000000000000000000000000000000
00000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111000000000000000000000000000000000
00000000000000000000000000000000000000011111111111111111111111111111111111111111111110000011100000000000000000000000000000000
00000000000000000000000000000000000000000000011111111111111111111111111111111111100000000011100000000000000000000000000000000
00000000000000000000000000000000000000111111111111111111111111111111111111111111111111110111100000000000000000000000000000000
请注意,每个1或0都是独立的,即值不是小数。我需要找到文件的列方式总和。总共有125列,有840946行。
我尝试了textread
,fscanf
和其他一些matlab命令,但结果是它们都以十进制格式读取每一行并创建一个840946x1
数组。我想创建一个840946x125
矩阵来计算列式和。
答案 0 :(得分:6)
您可以使用textread执行此操作。只需读取字符串,然后使用sscanf处理它们,一次一个数字
A = textread('data.txt', '%s');
ncols = size(A, 1);
nrows = size(A{1}, 2);
A = reshape(sscanf([A{:}], '%1d'), nrows, ncols);
请注意,现在A已转置,即您有125行。
然后简单地通过
计算逐列和colsum = sum(A);
答案 1 :(得分:5)
这是一种有点黑客攻击的方法:
A = textread('data.txt', '%s');
colsum = sum(cat(1,A{:})-'0')
细分:
textread
将读取0和1的每一行作为单个字符串。因此A
将是一个单元格字符串,每个元素都等于一个长度为125的字符串。cat(1,A{:})
将单元格字符串连接成大小为840946-by-125的“普通”Matlab字符数组。 'a'-0 = 97
,小写'a'的ASCII值。 sum
将最终总结此数组的列。