我有一个矩阵 A:“M x N”。我想在矩阵中运行一个函数,
例如,回归:设每一列为 Y,其余列为 X
for i=1:N
Y = A(:,i); % let Y be the "i"th columns
X = A; X(:,i)=[]; % let X be other columns
coef(:,i)=regress(Y,X);
end
我想知道是否有任何matlab函数能够在循环中处理一个函数
最佳答案
这应该快得多!
[n_rows, n_cols] = size(A);
ind = true(1,n_cols);
coef2 = zeros(n_cols - 1, n_cols);
for i=1:n_cols
y = A(:,i); % let Y be the "i"th columns
ind(i) = false;
X = A(:,ind); % let X be other columns
coef2(:,i)= X\y;
ind(i) = true;
end
我的代码和你的代码之间的区别:
- X\y 给出 y 在 X 上的回归系数。(最重要)
- 我不调整矩阵的大小。
关于algorithm - MATLAB:在矩阵中使用函数时避免循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33774434/