# Filling a matrix without for-loops and ifs

28 views (last 30 days)
Mauricio Garcia on 18 Sep 2019
Edited: James Tursa on 18 Sep 2019
So i have this piece of code:
for i = 1:L
n1 = M(i,1);
n2 = M(i,2);
for j = 1:N
if j == n1
A(i,j) = 1;
elseif j == n2
A(i,j) = -1;
else
A(i,j) = 0;
end
end
end
M is a (L,2) matrix which tells me where does a line start and where it ends.
What i am looking to do is fill a matrix "A" , that is already filled with zeros, with a 1 where the line starts [M(:,1)], and a -1 where the line ends [M(:,2)], and all other elements with zeros, line per line.
For example if my M matrix is:
M =
1 2
2 3
1 3
The matrix A would be:
A =
1 -1 0
0 1 -1
1 0 -1
What i would like to know, is if i can fill this matrix "A" without using for's and if's, just make my code cleaner and maybe faster to run.
I was talking with a professor and told me to do it like this:
A(ind(:,1) = 1
A(ind(:,2) = -1
But i feel something is missing and cant find how to do it properly.
Sorry for the long post, thank you for your time.
Cheers

James Tursa on 18 Sep 2019
Edited: James Tursa on 18 Sep 2019
Check out the sub2ind( ) function:
In particular, your code would look something like:
A = zeros(_____); % <-- You need to figure out what the size of A should be
A(sub2ind(_____)) = 1; % <-- You need to figure out the proper inputs for sub2ind( )
A(sub2ind(_____)) = -1; % <-- You need to figure out the proper inputs for sub2ind( )