试图找到各列的总和

时间:2015-05-01 17:09:01

标签: matlab for-loop

我必须在matlab中打开这个数据文件:

  • A 12 E 88
  • B 23 F 22
  • C 55 G 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

当我运行代码时,它不断给我这个错误:输入参数'mat'未定义。有人可以帮帮我吗?我真的很感激。谢谢。

1 个答案:

答案 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

这对我有用(在Octave中,我手边没有MATLAB机器),结果

ans =

     0   167     0   231

如果我误读了您的评论,并且您实际上想要总结所有列,请将2:2:col替换为1: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循环,那么可能需要一段时间来让您的大脑无法考虑在数组上显式迭代。