Reputation: 435
I have the above loop running on the above variables:
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.
Upvotes: 1
Views: 1088
Reputation: 26069
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.
Upvotes: 1
Reputation: 112699
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
Upvotes: 1