K>> mat=magic(4)>5
mat =
1 0 0 1
0 1 1 1
1 1 1 1
0 0 1 0
K>>
Here I would like to obtain 1 for the first row, 2 for the second row,
1 for the third row, and 3 for the fourth row.
[dum,idx]=sort(mat,2,'descend');
firstOne=idx(:,1)
HTH
Yi Cao
Yi Cao gave a nice solution.
This is another using arrayfun
mat=magic(4)>5
arrayfun(@(i) find(mat(i,:)~=0,1,'first'),1:size(mat,2))
ans =
1 2 1 2
--Nasser
btw, your mat from your magic(4)>5 command is different than what I get.
Your 4th row does not seem to be correct
EDU>> mat=magic(4)>5
mat =
1 0 0 1
0 1 1 1
1 1 1 1
0 1 1 0
EDU>> ver
-------------------------------------------------------------------------------------
MATLAB Version 7.7.0.471 (R2008b)
Which Matlab version did you use? what is your output for magic(4) ?
--Nasser
Sorry about that. I modified 'mat' by using mat(ind,ind) = 1 so that
it is not a result from magic(4)..
Thank you all for your help.
And yet a few others:
mat = magic(4)>5 % data
[c1,dummy] = find(mat.'==1 & cumsum(mat.',1)==1) % fast
[c,r] = find(mat)
c2 = accumarray(c,r,[size(mat,1) 1],@min)
hth
Jos
>
> [dum,idx]=sort(mat,2,'descend');
> firstOne=idx(:,1)
Beware of the result when a row is all-zero.
Bruno
[m where]=max(mat,[],2)
where=where.*(m==1) % 0 for all-zero row
Bruno
This only works if all matrix values are real and non-negative.
--
Loren
http://blogs.mathworks.com/loren
% Data
mat = round(rand(4)*3)
N = 3; % The number to find.
COLS = zeros(size(mat,1),1); % Could use zeros() or nan().
TMP = mat==N;
[r,c] = find(TMP & cumsum(TMP,2)==1);
COLS(r) = c
m = round(rand(9,4)*3)
[r,c] = size(m)
n = 3; % number to find.
idx = mod(sum(cumprod(double(m ~= n),2),2)+1,c+1)
I think that's pretty slick, Siyi. It does bring up a question: why does cumsum work on logicals but cumprod does not? I hadn't noticed that before.
and another route to Rome:
M = ceil(10*rand(10,8)) ;
val = 6 ;
[mx,idx] = max((M==val),[],2)
idx(mx==0) = 0
Jos
>
> and another route to Rome:
>
> M = ceil(10*rand(10,8)) ;
> val = 6 ;
>
Actually it's the same route as ... in post #8
Bruno