Droping elements in a matrix
조회 수: 2 (최근 30일)
이전 댓글 표시
I don't know how to put my question into a few simple sentences. So let's me explain my situation briefly and then ask the question.
Suppose I have one vector and one matrix. Let's assume that the vector is a column vector A = [1;2; ...;n]. Let's the matrix = B. The first column of matrix B is B(:,1) = [1;...;1;2;...;2; ...;n;...;n] with each element of A repeated in an ascending order.
Now suppose that A(i) is dropped from vector A for whatever reason. How can I tell MATLAB to drop the corresponding rows in B starting with i?
For example, if A becomes [1;3;...;n), what I want MATLAB to do is to get me B = [1;...;1;3;...;3;...;n;...;n]
Thank you!
댓글 수: 0
답변 (2개)
Walter Roberson
2012년 2월 20일
Assuming A has not yet had the element dropped:
B(i*length(A)+1:(i+1)*length(A), :) = [];
댓글 수: 2
Walter Roberson
2012년 2월 20일
The above code assumes that the element has not been dropped from A yet. If it _has_ been dropped, then the length() need to have one added to them.
I don't know now where I got the idea that the # of repeats was the same as the length of A. Let R be the number of repeats, and then the code should be (correcting for an off-by-one error I had)
B( (i-1)*R + 1 : i*R, :) = [];
Your question asked specifically about dropping A(i), so the code was written in terms of "i" designating which element should be affected.
You are correct that the code assumes each A is repeated equally.
If there are repeats in A, and "i" becomes a vector indicating which _consecutive_ elements of A are to be dropped, then
B( (min(i)-1)*R + 1 : max(i)*R, :) = [];
If the repeats are not consecutive, and are stored in the vector "i", then
B( reshape(bsxfun(@plus, (1:R).', R*(i-1)),[],1), :) = [];
Andrei Bobrov
2012년 2월 21일
eg
A = sort(randperm(9,6).')
B = arrayfun(@(i1)A(i1)*ones(randi([4 6]),1),1:numel(A),'un',0);
B = cat(1,B{:})
A = A([1:2,4:end]);
outB = B(ismember(B,A),:)
댓글 수: 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!