Reputation: 1448
Consider the matrix:
M = [1.0 2.0 3.0; 5.0 4.0 3.0; 1.0 100.0 12.0]
I want to get column of the max value in each row. So it should be:
col = [3; 1; 2]
, since
M[1,3] -> 3.0;
M[2,1] -> 5.0;
M[3,2] -> 100.00;
In Octave it is easy to achieve:
[max, col] = max(M,[],2)
, where col=[3;2;1].
In Julia I can find only findmax
function which returns an absolute index of the max element for each row.
So it would be:
max, aindx = findmax(M,2)
, where aindx=[7,2,6]
M[7] = 3.0; M[2] = 5.0; M[6] = 100;
Where to find Julia equivelent for Octave max(M,[],2)?
My current workaround:
max, aindx = findmax(M, 2);
msize=size(M);
col = zeros(msize[1], 1);
for i=1:msize[1]
_, col[i] = ind2sub(msize,aindx[i]);
end
Upvotes: 4
Views: 2684
Reputation: 12179
Julia's findmax
is more flexible than Octave's max
: you can find the maximum over multiple dimensions at once. As a consequence, it returns a linear index.
As you've noted, you can use ind2sub
to compute whatever index(es) you want. If you use this a lot, you might want to define your "workaround" as a function to make it convenient to use. You can put that function in your .juliarc.jl
if you want to make sure it's always available.
Upvotes: 6