Hungarian Algorithm! Removing rows and comluns from matrix
4 views (last 30 days)
Show older comments
Hi I don't have much experience with Matlab and I'm doing this project for school, the task is for implement the Hungarian Algorithm. I'm almost at the end but now I'm having problems with removing rows and columns. I'll put my code and an example to show, if someone could help me I would appreciate it.
Let's say I have this matrix A: 15 0 0 0; 0 50 20 25; 35 5 0 10; 0 65 50 65;
(bare in mind that ca has the positions of the columns to erase and la the positions for the rows to erase)
ca=[1 3]
la=[1]
for j=1:length(ca)
A5=A3;
y=0:n;
A5(:,ca(j)-y(j))=[];
for i=1:length(la)
A5(la(i)-y(i),:)=[];
end
end
What I noticed is that if I don't use the 'y' after the first loop (for j=1) it erases the right column but them the A5 matriz turns 4x3 and the third original column is now the second, so the loop ends up deleting the first and fourth rows. I tried adding y for making the second loop decrease in one value so the third column is now the second, but instead it returns
0 20 25
35 0 10
0 50 65
I can't see what is wrong. Can someone help me please?
0 Comments
Accepted Answer
Baalzamon
on 4 Dec 2012
Edited: Baalzamon
on 4 Dec 2012
So you are after: [50, 25; 5, 10; 65,65] ?
[nRowsA, nColsA] = size(A);
ca = [1 3]; la = 1;
nRowsOut = nRowsA - length(la); % Result should have this many rows
nColsOut = nColsA - length(ca); % Result should have this many columns
Logical array same size as input
maskA = true(nRowsA, nColsA);
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
% Change all rows to false that are given in variable la
maskA(la,:) = false;
0 0 0 0
1 1 1 1
1 1 1 1
1 1 1 1
% Change all cols to false that are given in variable ca
maskA(:,ca) = false;
0 0 0 0
0 1 0 1
0 1 0 1
0 1 0 1
% Now left with zeros for rows and columns we don't want.
trimmedA = A(maskA); % Extract elements from A using the maskA
50
5
65
25
10
65
% From example there were two columns over 3 rows
reshaped2array = reshape(trimmedA,nRowsOut, nColsOut);
50 25
5 10
65 65
The arrays you see are just output from the line above it and for some clarity in what is going on.
There probably is an easier way which no doubt someone will mention...
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!