Droping elements in a matrix

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

回答(2 个)

Walter Roberson
Walter Roberson 2012-2-20
Assuming A has not yet had the element dropped:
B(i*length(A)+1:(i+1)*length(A), :) = [];
  2 个评论
nfllover
nfllover 2012-2-20
Thank you very much Walter. What if A has not had its element dropped? Also, if no element in A has been dropped, how does the code above know which element in B to drop? I assume that the code above is based on the assumption that each element in A is repeated n times equally in B. I could be wrong. But what is it is not the case? What if there are, say, 2 1s and 4 2s in B?
Walter Roberson
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
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),:)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by