Filling a matrix without for-loops and ifs

조회 수: 33 (최근 30일)
Mauricio Garcia
Mauricio Garcia 2019년 9월 18일
편집: James Tursa 2019년 9월 18일
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

답변 (1개)

James Tursa
James Tursa 2019년 9월 18일
편집: James Tursa 2019년 9월 18일
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( )

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by