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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!