MATLAB: Vectorize a doble loop for

for loopvectorize

Hi everyboy
I am trying to vectorize the following code, but I can't. I want to calculate the matrix p_hat from the matrixs p and omega (these last matrix are of the same order) . The vector a is a function that gives me another index.
Could anyone help me, please?
for k=1:length(a)
for j=1:length(a)
if omega(j,k)==1
p_hat(k,a(j))=p(j,k);
end
end
end

Best Answer

Assuming that omega is a logical matrix (please post what the inputs are, such that the readers do not have to guess the details):
p_hat = zeros(length(a), length(a)); % Needed only if p_hat is existing before
p_hat(:, a) = (p .* omega).';
Some assumed test data:
omega = rand(10, 10) > 0.2;
a = randperm(10);
p = rand(10, 10);
p_hat2(:, a) = (p .* omega).'; % Vectorized
p_hat = zeros(length(a), length(a)); % Loop
for k=1:length(a)
for j=1:length(a)
if omega(j,k)==1
p_hat(k,a(j))=p(j,k);
end
end
end
isequal(p_hat, p_hat2) % Compare
>> logical(1)
Related Question