Filling a matrix without for-loops and ifs

36 次查看(过去 30 天)
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