ChuNan
ChuNan

Reputation: 1151

find out the largest element from the given row to the end

Suppose I have a matrix a and a given row number list for each column:

>> a=magic(5)

>> a =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

>> b=[2 3 4 5 1];  %% Note that the elements in b is arbitrary

Now I want to find the maximal values from column 1, row 2:end,and column 2, row 3:end, ... ,and column 5, row 1:end respectively, is there a method without using for-loop? I tried a(b:end,:) but it starts all from b(1) for each column.

Upvotes: 2

Views: 64

Answers (4)

Stewie Griffin
Stewie Griffin

Reputation: 14939

Here is another possibility using arrayfun:

res = arrayfun(@(n) max(a(b(n):end,n)),1:numel(b))

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112769

Set non-wanted entries to NaN and then use max:

ind = bsxfun(@lt, (1:size(a,1)).', b); %'// logical index
a(ind) = NaN; %// set those entries to NaN
result = max(a); %// compute maximum of each column

This works for arbitrary b (not necessarily in diagonal form).

Upvotes: 2

Matt J
Matt J

Reputation: 1137

 result = max(a-triu(inf(size(a)),1),[],1)

Upvotes: 0

venergiac
venergiac

Reputation: 7727

diagonal?

 [m n] = size(a); 
 [tril(a(:,1:n-1),-1), a(:,n)]

then

max([tril(a(:,1:n-1),-1), a(:,n)])

result

23 18 25 2 22

Upvotes: 0

Related Questions