Selecting and exporting rows from matrix

2 次查看(过去 30 天)
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-

采纳的回答

Guillaume
Guillaume 2015-2-9
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 个评论
Jasper
Jasper 2015-2-12
Follow-up question: is there a quick(er) way to make 2 cell arrays that hold either the partial matrices indicated by '1' or the ones indicated by '0'? This is what I have now:
n = length(splitcoords(:,1));
Cell_Zeros = cell(0);
Cell_Ones = cell(0);
for i = 1:n
if splitcoords{i,1}(1,4) == 0
Cell_Zeros = vertcat(Cell_Zeros, splitcoords{i,1});
else
Cell_Ones = vertcat(Cell_Ones, splitcoords{i,1});
end
end
Although not too slow and useful as it is, I'm just curious if the loop can again be replaced by single line commands...?
Thanks again!
Guillaume
Guillaume 2015-2-12
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by