Selecting and exporting rows from matrix
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jasper
el 9 de Feb. de 2015
Comentada: Guillaume
el 12 de Feb. de 2015
Hello,
I have a number of coordinates around the origin (1st and 2nd quadrant) in a big matrix that I need to filter appropriately. Here's an example:
x = [2 3 2 5 1 3 4 -3 -4 -3 -6 2 4 1 3 2]'; %some x
y = [1 3 4 1 2 4 2 0.4 0.6 1 1 3 1 2 4 5]'; %some y
Coords = [x,y];
Coords(:,3) = atan2d(y,x); %angle with origin
for i = 1: 16
if Coords(i,3) > 150 %treshold
Coords(i,4) = 1;
end
end
So I have identified all coordinate pairs that are in a certain area in quadrant 2 (numbered '1'). Now what I want to do is go through the matrix and divide that in three smaller matrices/ 'chunks', i.e. a first matrix of 7x4 (all indicated by 0), a second 4x4 (indicated by 1s) and a third 4x5 (0s again). Any idea how to do this in a loop so that variable 'chunk' lengths are possible to incorporate? I guess I need something in the loop that uses the switch from 0 to 1 and back and uses that to export?
Many thanks in advance!
-J-
0 comentarios
Respuesta aceptada
Guillaume
el 9 de Feb. de 2015
Loops are not required at all for what you're doing. You can replace your loop with the single line:
Coords(:, 4) = Coords(:, 3) > 150;
Now to find your transitions, diff and find will tell you where they are:
beforetransitionrows = find(diff(Coords(:, 4)));
You can then use these values to split your matrix with mat2cell. Another diff will give you the height of each submatrix (required by mat2cell):
submatricesheight = diff([0 beforetransitionrows' size(Coords, 1)]);
splitcoords = mat2cell(Coords, submatricesheight, size(Coords, 2))
3 comentarios
Guillaume
el 12 de Feb. de 2015
Yes, certainly. You already know where the submatrices start (1st one at row one, the others at beforetransitionrows + 1, so use that
cellstate = Coords([1; beforetransitionrows + 1], 4);
cell_ones = splitcoords(cellstate == 1)
cell_zeros = splitcoords(cellstate == 0)
As a side note, I never use length. I prefer numel when dealing with vectors or size and an explicit dimension. The problem is length is the size of the largest dimension, so it can be the number of columns, rows, pages, etc. depending on which is the largest. It's very rare you don't care which dimension that is.
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!