简体   繁体   中英

MATLAB: avoid loop when using a function within a matrix

I have a matrix A: "M x N". I want to run a function within a matrix,

eg,regression: let each column be a Y, rest column be Xs

    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

i wonder if there is any matlab function is able to handle a function in a loop

This should be MUCH faster!

[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

Differences between my code and yours:

  1. X \\ y gives you regression coefficients of y on X. (Most important)
  2. I don't resize matrices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM