Search code examples
matlabcell-array

Using logical indexing on a specific set of rows in MATLAB


I want to return the rows in a cell array which meet a condition that is repeated every few (but variable) lines. For example if my data is x,y,z coordinates split up into i slices where each slice{i} is a specific z I could have something that looks like this.

1,3,10
1,4,10
1,5,10
2,3,10
2,4,10
3,1,10

For each x I want to return the rows containing the max and min y values. So in this case I want rows 1, 3, 4, 5, 6.

The code I have now looks like this

idx = slice{i}(start:finish,2) == miny | slice{i}(start:finish,2) == maxy;
return = slice{i}(idx, :);

But the line slice{i}(idx, :) looks through the entire array from the beginning. I want to restrict this line to a certain subset.

Something like

slice{i}(idx, start:finish)

but this doesn't work.

Am I missing some syntax or do I need to approach the routine in a different way? (I know I haven't provided enough information for help in changing approach but I am assuming there is some way to do this by restricting the row indicies)

edit:

I found a workaround by creating

dummy = slice{i}(start:finish, :);    

and then just returning over the dummy matrix.


Solution

  • See if this works for you -

    %// Convert slice to a nuemric array
    slicenum = cell2mat(slice)
    
    %// Create the offset arary to be added with the local max-min indices to
    %// get the global(actual) row indices for idexing into slicenum or slice
    offset1 = [0 ; find(diff(slicenum(:,1)))]
    
    [~,~,unqX] = unique(slicenum(:,1))
    
    %// Get local max and min row indices
    max_row_ind = accumarray(unqX,slicenum(:,2),[],@max_ind) + offset1
    min_row_ind = accumarray(unqX,slicenum(:,2),[],@min_ind) + offset1
    
    %// Get global row indices and use them to index into slicenum for the output
    max_y_slice = slicenum(max_row_ind,:)
    min_y_slice = slicenum(min_row_ind,:)
    

    Associated functions -

    function ix = max_ind(array1)
    [~,ix] = max(array1);
    return;
    
    function ix = min_ind(array1)
    [~,ix] = min(array1);
    return;