LisaB
LisaB

Reputation: 75

Equalize to zero a different element of a matrix for each row without loop

I have an IxS matrix called numerateur and I would like to set one element per row to zero. However, the column to which this element belongs changes for each row. I can do it with a loop but would like to use a more efficient method.

You can find my loop below:

choice is an Ix1 vector containing, for each row, the column number of the element I want to set to zero in numerateur.

for i = 1:I
        rank1 = choice(i);
        numerateur(i,rank1) = 0;
end

Upvotes: 2

Views: 101

Answers (2)

rahnema1
rahnema1

Reputation: 15867

Use implicit expansion to find logical indices:

numerateur(choice == 1:size(numerator,2)) = 0;

Alternatively you can use sparse matrix to generate logical indices:

numerateur(sparse(1:I,choice,true,I,S)) = 0;

Upvotes: 4

Luis Mendo
Luis Mendo

Reputation: 112759

You need to convert the column indices to linear indices:

ind = (1:size(numerateur,1)) + (choice(:).'-1)*size(numerateur,1);
numerateur(ind) = 0;

Example:

>> numerateur = randi(9,5,7)
numerateur =
     8     7     8     3     2     8     4
     7     8     6     3     6     1     3
     8     9     5     5     5     9     5
     4     4     2     7     4     9     9
     1     6     7     3     8     7     9
>> choice = [2; 3; 6; 5; 1];
>> ind = (1:size(numerateur,1)) + (choice(:).'-1)*size(numerateur,1);
>> numerateur(ind) = 0;
>> numerateur
numerateur =
     8     0     8     3     2     8     4
     7     8     0     3     6     1     3
     8     9     5     5     5     0     5
     4     4     2     7     0     9     9
     0     6     7     3     8     7     9

Upvotes: 4

Related Questions