Wednesday, May 13, 2009

Matlab: indexing; find first value in each row

OP here.

Q:
How can I find the first index of certain value in each row without using a for loop?

A1:
m = round(rand(9,4)*3); % the data;
[r,c] = size(m);
n = 3; % number to find.

idx = mod(sum(cumprod(double(m ~= n),2),2)+1,c+1)


A2:
idx = zeros(size(m,1),1);
tmp = m == n;
[r,c] = find(tmp & cumsum(tmp,2) == 1);
idx(r) = c;


A3 (fastest):

[v,idx] = max(m == n,[],2)
idx = idx.*(v==1);
% or idx(v==0) = 0;


Speed test:

% m = round(rand(1600000,4)*3);
A1:
Elapsed time is 0.293340 seconds.
A2:
Elapsed time is 0.407424 seconds.
A3:
Elapsed time is 0.110964 seconds.

No comments: