Darcy
Darcy

Reputation: 659

Replace diagonal elements only in rows specified by a vector of row indices? (MATLAB)

I have an N x N matrix, A, and a vector of row indices, v. I want to replace the diagonal elements of A only for the rows in A specified by v without using a for loop.

For example:

N = 10;
A = rand(N,N); %Random N x N matrix

v = [1 4 6 9 10]; %vector of row indices

%What I want to do but without a for loop:
for i = 1:length(v)
    A(v(i),v(i)) = 0;
end

%I thought this would work, but it does not:
%A(v,v) = 0;

I feel like there must a one-line method of doing this, but can't seem to figure out what it would be.

Cheers

Upvotes: 0

Views: 45

Answers (1)

Phil Goddard
Phil Goddard

Reputation: 10782

Use sub2ind:

A(sub2ind(size(A),v,v)) = 0;

Upvotes: 5

Related Questions