Deleting rows in a matrix
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I have two matrices which are generated in a loop for n years:
A (m-rows x n-columns) B (k-rows)
Matrix B includes values which represent row numbers of matrix A that should be deleted. So, I want for every value in matrix B, the corresponding row in matrix A to be deleted.
For example,
A=[1 2; 2 2; 3 4], B= [2]
The result should be a matrix [1 2;3 4]. I.e. the middle row is deleted as B includes value 2.
For some reason I'm not able to find the correct coding for this. I tried several things, but inside the loop it doesn't work. This is what I tried, but this does't work:
for j= 1:n
B;
for i= 1:length(B)
indices = find(A(:,1)==B(i));
A(indices,:) = [];
end
end
Can anyone help me with this?
2 个评论
James Tursa
2015-8-11
Does B really contain the row numbers, or does it contain values that must match values in the first column of A? Your words say the former but the code looks like the latter.
采纳的回答
Brendan Hamm
2015-8-11
If you want to delete the second row because B has the value 2 you can use this vector to index into A as such:
A(B,:) = [];
That is how I interpret the question you pose, but the code seems to approach a different problem, outlined below.
If you want to delete the second row because the first element of A is 2, then you would find if each element of the first column of A is in the vector B and delete those locations:
locA = ismember(A(:,1),B); % Logical vector (true if A(i,1) is in B, false otherwise)
% use the logical vector to index into A and delete
A(locA,:) = [];
2 个评论
Brendan Hamm
2015-8-11
I am a bit confused with your question here still, what is not working specifically? Does this work fine on the first iteration of the loop? Is it that you are overwriting the excel file at every iteration of the loop? Are you receiving any errors?
Taking a stab at it:
If UitDienst is a matrix and not a vector as in the example you gave, then you likely do not want to perform a linear indexing as you do with
UitDienst(j)
Matlab is a column major language which means that elements of a matrix are stored column by column:
A = [1 2 3; 4 5 6]
is stored in memory as [1 4 2 5 3 6] (column-by-column) This means that A(2) will return the value 4, A(3) will return the value 2, etc. It seems that maybe you need to change that to read:
UitDienst(:,j)
更多回答(2 个)
James Tursa
2015-8-11
编辑:James Tursa
2015-8-11
"Matrix B includes values which represent row numbers of matrix A that should be deleted"
Assuming this is exactly what you want, then this will do the job:
A(B,:) = [];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!