Filling a matrix without for-loops and ifs

37 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by