Max value of row in matrix and creating new matrix
1 view (last 30 days)
Show older comments
I want something like this matrixa=[12 33 44;26 59 14;15 99 54] matrixb=[26 89 95;23 54 12;2 54 43]
and to get output like this
matrixc=[15 99 54;26 89 95]
calculate the sum of rows in both matrix and to create a new matrix with the two rows that have the greatest sum value like example above. can it be done with max function ? thanks in advance :)
2 Comments
Answers (2)
Star Strider
on 7 Oct 2014
This works:
sa = sum(matrixa,2);
sb = sum(matrixb,2);
c = zeros(size(matrixa));
q1 = matrixa(sa > sb,:);
q2 = matrixb(sb > sa,:);
c(sa > sb,:) = matrixa(sa > sb,:);
c(sb > sa,:) = matrixb(sb > sa,:);
3 Comments
Star Strider
on 7 Oct 2014
Misread it at first. This works:
sa = sum(matrixa,2);
sb = sum(matrixb,2);
mab = [matrixa; matrixb];
sab = [sa; sb];
[srtab,ix] = sort(sab,'descend');
matrixc = mab(ix(1:2),:);
Star Strider
on 8 Oct 2014
With respect to your solution, what happens if the two largest row sums happen to be in the same matrix?
My code accounts for that, so that ‘c’ contains the rows of either matrix with the largest row sums.
Your code selects the largest row sums from ‘matrixa’ and ‘matrixb’. They may not be the largest row sums of the two matrices.
See Also
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!