简体   繁体   中英

how to make matlab loop over 2d array faster

I have the above loop running on the above variables:

  • A is a 2d array of size mxn.
  • mask is a 1d logical array of size 1xn
  • results is a 1d array of size 1xn
  • B is a vector of the form mx1
  • C is a mxm matrix, m is the same as the above.

Edit: expanded foo(x) into the function.

here is the code:

temp = (B.'*C*B);    
for k = 1:n
    x = A(:,k);
    if(mask(k) == 1)
        result(k) = (B.'*C*x)^2 / (temp*(x.'*C*x)); %returns scalar
    end
end

take note, I am already successfully using the above code as a parfor loop instead of for. I was hoping you would be able to suggest some way to use meshgrid or the sort to yield better performance improvement. I don't think I have RAM problems so a solution can also be expensive memory wise.

Many thanks.

If your foo admits matrix input, you could do:

result = zeros(1,n); % preallocate result with zeros
mask = logical(mask); % make mask logical type
result(mask) = foo(A(mask),:); % compute foo for all selected columns

try this:

 result=(B.'*C*A).^2./diag(temp*(A.'*C*A))'.*mask;

This vectorization via matrix multiplication will also make sure that result is a 1xn vector. In the code you provided there can be a case where the last elements in mask are zeros, in this case your code will truncate result to a smaller length, whereas, in the answer it'll keep these elements zero.

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