Question

I'm trying to find the first 1 in each column of a matrix without using a for or a while. Say I have

-->A
 A  =

    1.    0.    0.    0.  
    0.    0.    1.    1.  
    1.    0.    1.    1.  
    1.    1.    0.    0. 

then I would like to obtain [1,4,2,2] (I can assume there is always a 1 somewhere in each column). The thing is when I use find(A), it gives me [1,3,4,8,10,11,14,15].

I was told not to use loops but matrix operations because scilab handles the last ones better.

Thank you in advance!

Était-ce utile?

La solution

With such a small matrix performance could be fast enough with a for loop and probably more readible. But one solution avoiding the use of for loops could be as following.

//Find all rows and cols of the ones in A
[row,col] = find(A);

//Get all row positions that are in a new column index
disp( row( find([1,diff(col)]) ));

I think a more readible solution would be something like the following:

//For each column
for col=1:4

   //Find only the first occurence
   disp(find(A(:,col),1));

end

As mentioned, with such a small matrix readibility should be a higher priority. You could measure performance of both (or other) solutions by profiling.

If you like to read more about some performance enhancing techniques have a look here.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top