简体   繁体   中英

how can I find the place of some numbers in a Matlab matrix?

I have a matrix with values from -180 to 180 and I want to find all the places where each value is and then save them in a new matrix, how can I do it?

I want to create a for loop that goes for values -180:1:180 and finds all the locations(i,j) for each value. eg I want to find all the locations for value -180 and then save them in a new matrix. is it possible to be done? I wrote here the code for the loop function and it works but I don't know how to save the values so as to know which location is for each value.

for a= 180:-1:-180

   [i,j]=find(ORIENT==a)     
end

So many ways to do this.Assuming that ORIENT is the matrix, you could use cells to store the i's and j's, like:

ORIENT=round(180.*(2.*rand(100,100)-1)); %or whatever
find_results=cell(361,2);
a=-180:1:180;
for index=1:length(a)
   [i,j]=find(ORIENT==a(index));
   find_results{index,1}=i;
   find_results{index,2}=j;     
end

Not very elegant or efficient, but it works fine for me. I know you wantted to use matrix, but as you cant freely choose the length of each column in the matrix, I think this will do. Otherwhise you could go like

find_results(index,1:length(i))=i;

But you need to first create the matrix which will end up filled with zeros,because the only way for this to work is to make sure size(find_result,1)=number of elements in the matrix(cells dont care). You could use a sparse matrix but man, it is getting out of hand.

--------------------------edit---------------------------------------

I guess you could do something like this for a matrix, but size will be huge:

ORIENT=round(180.*(2.*rand(100,100)-1)); %or whatever
a=-180:1:180;
find_results_i=nan(size(ORIENT,1).*size(ORIENT,2),size(a,2));
find_results_j=nan(size(ORIENT,1).*size(ORIENT,2),size(a,2));
for index=1:length(a)
   [i,j]=find(ORIENT==a(index));
   find_results_i(1:length(j),index)=i;
   find_results_j(1:length(j),index)=j;     
end

If you are familiar with sparse, use

find_results_i=sparse(size(ORIENT,1).*size(ORIENT,2),size(a,2));
find_results_j=sparse(size(ORIENT,1).*size(ORIENT,2),size(a,2));

To save a ton of memory, altougth it will be slower

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM