Matlab 尝试以特定方式格式化预先存在的表

Matlab 尝试以特定方式格式化预先存在的表,matlab,Matlab,我有一个尺寸为3500 x 20的数据集 我想做的是首先删除它的前2列,留下18列 现在我想用平均值的一列替换每3列。例如,删除前2列后,取新列1-3的平均值并将其存储为新矩阵中的一列,然后取列4-6的平均值并将其存储为新矩阵中的下一列,然后取列7-10的平均值并将其存储为下一列 这是我迄今为止的尝试: function newMatrix = preprocess(originalMatrix) nrows = size(originalMatrix, 1); % number of rows

我有一个尺寸为3500 x 20的数据集

我想做的是首先删除它的前2列,留下18列

现在我想用平均值的一列替换每3列。例如,删除前2列后,取新列1-3的平均值并将其存储为新矩阵中的一列,然后取列4-6的平均值并将其存储为新矩阵中的下一列,然后取列7-10的平均值并将其存储为下一列

这是我迄今为止的尝试:

function newMatrix = preprocess(originalMatrix)
nrows = size(originalMatrix, 1); % number of rows of original table (3500)
ncolsOriginal = size(originalMatrix,2); % number of cols of original table (20)
ncolsNew = (ncolsOriginal - 2)/3 % number of cols of the new matrix we want (18/3 = 6)
originalMatrix = table2array(originalMatrix(:,3:ncolsOriginal)) % convert original table to matrix
newMatrix = zeros(nrows, ncolsNew) % initialise new matrix
for i = 1:ncolsNew:3
    newMatrix{:,i} = mean(originalMatrix(i:i+2)'); % calculate mean of 3 sets of columns at a time and store it as a single column in new matrix. 
end
end
在最后一行(倒数第二个“end”之前),我得到了以下错误:

Cell contents assignment to a non-cell array object.

有人知道为什么会这样吗?如果有人能给我一些建议,我将不胜感激

代码中的问题是在for循环中使用大括号
{}
进行索引。这些是为单元阵列保留的。对于正规矩阵,必须使用正规括号
()
。那么您的代码应该可以工作(尽管我没有验证)

然而,通过将原始矩阵矢量化到一个空间中,可以很容易地将这个问题矢量化,在这个空间中,您只需沿着一维进行计算

我们的目标是制作一个3D矩阵,其中第一个维度(列)仍然是相同的列。我们选择沿第二维度取平均值,所以它的长度应该是3,并且包含3列,这3列应该是平均值。最后,第三维包含6个结果列。 我们可以通过

reshape(originalMatrix,size(originalMatrix,1),3,[])
然后我们可以很容易地沿着第二维度取平均值:

mean(reshape(originalMatrix,size(originalMatrix,1),3,[]),2)
这就给我们留下了一个
2000x1x6
矩阵,其中包含所需的结果。要删除大小
1
维度,我们需要使用矩阵

squeeze(mean(reshape(originalMatrix,size(originalMatrix,1),3,[]),2))
所以函数变成

function newMatrix = preprocess(oldMatrix)
    originalMatrix = table2array(originalMatrix(:,3:end))
    newMatrix = squeeze(mean(reshape(originalMatrix,size(originalMatrix,1),3,[]),2))
end
我希望这有帮助

function newMatrix = preprocess(originalMatrix)
    matrixTmp = originalMatrix(:,3:20);

    [rows, cols] = size(matrixTmp);
    newCols = cols/3;
    newMatrix = zeros(rows, newCols);

    count = 1;
    for i=1:3:cols
        tmp = matrixTmp(:,i:i+2);
        newMatrix(:,count) = mean(tmp, 2);
        count = count + 1;
   end
end