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

2 Comments

" The vector a is a function that gives me another index"
It can't be both: is it a vector, or a function?
It is a vector

Sign in to comment.

 Accepted Answer

Jan
Jan on 2 Jun 2018
Edited: Jan on 2 Jun 2018
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)

3 Comments

Yes, it works. But how to vectorize de outer loop? Maybe something like
p_hat(1:length(a), a_aux(omega(:, 1:length(a)))) = p(omega(:, 1:length(a)), 1:length(a));
See the edited answer.
Thanks a lot!

Sign in to comment.

More Answers (1)

Bruno Luong
Bruno Luong on 2 Jun 2018
Edited: Bruno Luong on 2 Jun 2018
p = rand(3,4)
a = ceil(10*rand(size(p,1),1))
omega = rand(size(p))>0.4
[j,k] = find(omega)
p_hat = accumarray([k,a(j)],p(omega))

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!