2015-05-01 29 views
-1

的我都开在MATLAB这个数据文件的总和:试图找到各个列

  • 甲11 E 88
  • 乙23女性22
  • Ç55g的77
  • d 66 H 44

我把它命名为Thor.dat,这是我在MATLAB代码

fid = fopen('Thor.dat') 

if fid == -1 
    disp ('File open not successful') 
else 
    disp ('File open is successful') 

mat = textscan(fid,'%c %f %c %f') 

[r c] = size(mat) 

matcolsum 

fclose(fid) 
end 

这是我使用添加数值列功能:

function outsum = matcolsum(mat) 
% matcolsum finds the sum of every column in a matrix 
% Returns a vector of the column sums 
% Format: matcolsum(matrix) 

[row, col] = size(mat); 

% Preallocate the vector to the number of columns 
outsum = zeros(1,col); 

% Every column is being summed so the outer loop 
% has to be over the columns 
    for i = 1:col 
    % Initialize the running sum to 0 for every column 
    runsum = 0; 
    for j = 1:row 
     runsum = runsum + mat(j,i); 
    end 
    outsum(i) = runsum; 
end 
end 

当我运行的代码,它不断给我这个错误:输入参数“垫”是不确定的。任何人都可以请帮我吗?我真的很感激。谢谢。

+0

我和j被matlab使用,不建议将它们用作循环计数器。 – bilaly

+1

请注意'textscan'的输出是一个单元格数组(这里是'mat'),因此您需要使用大括号{}访问数据。 –

+0

这里我不清楚你的预期输出是什么。你想总结...字符代码吗?预期结果的例子将非常有帮助。 –

回答

0

如果根据你的评论,你想要的是数字(又名偶数,在你的例子中)列的总和,你的代码可以变成这个(为了清晰起见,我交换了行和列迭代):

function outsum = matcolsum(mat) 
% matcolsum finds the sum of every column in a matrix 
% Returns a vector of the column sums 
% Format: matcolsum(matrix) 

[row, col] = size(mat); 
outsum = zeros(1,col); 

for i = 1:row 
    for j = 2:2:col 
     outsum(j) = outsum(j) + mat(i,j); 
    end 
    end 
end 

这个工作对我来说(在八度,我没有一台机器用MATLAB在手),并导致

ans = 

    0 167  0 231 

如果我误解你的意见,你其实是想总结所有只需更换2:2:col1:col

但是,这是一种非MATLAB类。 MATLAB可以更好地处理具有更高级别向量函数的向量和矩阵,如果您想充分利用您的硬件(尤其是并行性),这是最好的。

你可以这样简单地写:

mat = ["A", 23, "E", 88; 
     "B", 23, "F", 22; 
     "C", 55, "G", 77; 
     "D", 66, "H", 44] 

[row, col] = size(mat); 
sum(mat(:,2:2:col)) 

从而造成

ans = 

    167 231 

,一旦你知道mat(:,i)是矩阵mat的第i列的含义应该是不言自明并且a:i:b是数字{a, a+i, a+2i, ...}

如果你已经习惯了C风格的for循环,它可能需要一段时间才能解散你的大脑,从思考迭代到数组上。

+0

谢谢。我认为你的方法有效。它只是我有一个单元格数组中的矩阵,所以它不断给我这个错误:???在赋值A(I)= B中,B和 中的元素数目必须相同。 任何想法这是什么意思? – Logan

+0

您可能希望使用http://mathworks.com/help/matlab/ref/cell2mat.html将您的单元格数组转换为普通矩阵。 –

+0

cell2mat是用于具有相同数据类型的单元阵列:( – Logan