Creating a dilution rule matrix - help needed

조회 수: 2 (최근 30일)
Asher Metzger
Asher Metzger 2015년 4월 24일
댓글: Asher Metzger 2015년 4월 24일
Hey there,
I have some difficulty with what seems to be a pretty simple code. I am trying to create a small code that makes a dilution rule for pipe salinity leaving a node. for example: if I have a [ 1; 1; 1; 2; 2; 2; 3] node vector for pipes leaving nodes (the pipe vector is: [1;2;3;4;5;6;7])
I would like to get a matrix:
[1 -1 0 0 0 0 0; 1 0 -1 0 0 0 0; 0 0 0 1 -1 0 0; 0 0 0 1 0 -1 0]
this matrix will then be multiplied by the salinity vector in pipes and I will make sure it equals zero. The question is how to get the matrix above.
this is what I have:
node_1 = [1; 1; 1; 2; 2; 2 ; 3];
pipe=1:7;
count=1;
B0=[];
for i=1:size((node_1),1)
for j=i+1:size(node_1,1)
if node_1(i)==node_1(j)
B0(count,pipe(i))=1;
B0(count,pipe(j))=-1;
count=count+1;
end
end
end
of course this doesn't work because I get two extra rows for the 2 and 3 pipes and the 5 and 6 pipes. In addition I keep on repeating the B0(count,pipe(i))=1; for a node, that has more than 2 pipes leaving it, which is wasteful.
I tried different kinds of solutions but they all seem faulty.
I hope the description of the problem is clear.
Thanks in advance, Asher

채택된 답변

Guillaume
Guillaume 2015년 4월 24일
The bit you should have explained better is the construction rule of your matrix. The way I understand it, for numbers that are repeated, create a row in your matrix for each repeat where:
  • first occurence occuring on row fi is marked 1 in column fi
  • row ri of subsequent occurences are marked -1 in column ri
This may work for this:
nodes = [1; 1; 1; 2; 2; 2; 3];
pipes = 1:numel(nodes);
B0 = [];
[uniq, pos] = unique(nodes);
for node = uniq'
nodepipes = pipes(nodes == node);
if numel(nodepipes) > 1
pipeout = nodepipes(1);
for pipein = nodepipes(2:end)
Brow = zeros(1, numel(nodes));
Brow(pipeout) = 1;
Brow(pipein) = -1;
B0(end + 1, :) = Brow;
end
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by