Updating a matrix through a loop

3 views (last 30 days)
Morgan Dubaz
Morgan Dubaz on 3 Feb 2020
Edited: dpb on 4 Feb 2020
Hello,
I have the matrix below:
0 0 0 0 1 1 0 1 1 0 1 0 1
1 0 1 1 1 0 0 1 0 1 0 0 1
0 1 0 1 0 1 0 1 1 0 1 1 1
1 0 1 0 1 1 1 1 0 0 1 0 0
0 0 0 0 1 0 1 0 1 0 0 0 0
1 0 0 0 0 0 0 1 0 0 0 0 1
I want to take this matrix and find the row that has the maximum entries (so in this case since all entries are ones, it would be the row with the highests sum; however, I will later be using matrices with larger values and only the number of entries will matter). I then want to save that row number somehow and then delete all the columns that have an entry in that row and then display the new matrix that was created from doing this. I want to repeat this process until there is only one column left OR there is no longer a row that has the maximum number of entries. At the end, I will need a list of all the rows that had the maximum number of entries for each iteration.
Any help is appreciated! Thank you!

Answers (1)

dpb
dpb on 3 Feb 2020
Edited: dpb on 4 Feb 2020
>> nR=sum(m~=0,2); % the number by row nonzero entries
>> m(:,any(m(nR==max(nR),:),1))=[] % remove columns with that many elements that have any entry in column
m =
0 0 1 0 0
1 1 1 0 1
0 0 0 0 0
1 1 1 1 0
0 0 1 1 0
1 0 0 0 0
>>
The above gets the end result without iterating by logical indexing/addressing.
The summary information is in
>> [nRmax,iRmax]=max(nR)
nRmax =
8
iRmax =
3
>>
contains the desired row, number information for the maximum number but the index will be only the first row if there are more than one; hence the logical indexing expression above that returns all locations matching as TRUE
If you must have the intermediary results along the way, iterate over the vector:
idmax=find(nR==max(nR));
which will contain the rows matching the maximum number elements.

Categories

Find more on Creating and Concatenating Matrices 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!