Reputation: 235
I have a matrix as shown in below:
A=[2 4;1 3;8 6;5 1;4 9]
now i need to extract the matrix A into 2 parts:
newpoint=[2 4];
rest=[1 3;8 6;5 1;4 9];
then apply loop again to extract the second column as new point :
newpoint=[1 3];
rest=[2 4;8 6;5 1;4 9];
Applying loop again to take third column number as new point :
newpoint=[8 6];
rest=[2 4;1 3;5 1;4 9];
Take the number in row sequence until the last row . Can someone be kind enough to help.Thanks~
Upvotes: 0
Views: 192
Reputation: 1200
Apart from HebeleHododo's answer, if you have big matrices maybe you can try this:
A = [2 4; 1 3; 8 6; 5 1; 4 9];
B = zeros(size(A,1)-1,size(A,2));
for idx = 1:size(A, 1)
newpoint = A(idx, :);
B(1:idx-1,:) = A(1:idx-1,:);
B(idx:end,:) = A(idx+1:end,:);
% do stuff
end
It doesn't get rid of the for
loop, but the temporary B matrix is pre-allocated and the copy between A and B is clear, which makes it quicker.
For A = rand(100000,2);
HebeleHododo's method takes ~123 seconds in my computer
and the one above takes ~85 seconds.
Edit: Just for reference, the timing is done using Intel Core i5-3450 CPU @ 3.10GHz
and Matlab R2011b
Upvotes: 2
Reputation: 3640
You said you want to extract columns, but gave examples with rows. I am going ahead and assuming you meant rows.
You can do it with a for loop.
A = [2 4; 1 3; 8 6; 5 1; 4 9];
for idx = 1:size(A, 1)
newpoint = A(idx, :);
rest = A; % Copy A to rest
rest(idx, :) = []; % Remove newpoint line
% do stuff
end
Results of first two iterations:
newpoint =
2 4
rest =
1 3
8 6
5 1
4 9
newpoint =
1 3
rest =
2 4
8 6
5 1
4 9
This is not a good method if your A
matrix is big.
Edit: In fact, do not use this method. George Aprilis timed it and found 123 seconds for a 100000x2 matrix. I guess my computer is much slower. It took 216 seconds. I repeat, do not use this.
Upvotes: 2