Extracting first n values of a matrix
조회 수: 205 (최근 30일)
이전 댓글 표시
I have a random matrix containing values from 1-50 of length 1000. I want to extract first 30 numbers of 10-20 to put in another matrix.
a= [1 5 1 2 5 8 7 4 1 2 5 1 5 5 20 24 50 4 11 25..........]
so the resulting matrix should contain
b= [20 11 ,........]
I checked that every number from 10-20 occurs atleast 30 times. For example no of 10's in matrix a is 32, number of 11's is 35 and so on. i want to balance this occurance to 30 each so that new matrix 10-20 should be of length 330. (containing 10,11,12,...20 all 30 times each).
how can i do that?
댓글 수: 2
Jan
2019년 4월 29일
편집: Jan
2019년 4월 29일
@ARN: Please do not advertise your question in the section for comments in otehr threads. If anybody does this, the forum would be full of noise.
I do not understand the question. If the output should contain the numbers between 10 and 20, why is there a 24, 50 and 25?
Do you mean, that you want to delete all occurences of the elements inside [10:20], if their number exceeds 30? If so, which elements do you want to remove? At the beginning, end, or random location?
채택된 답변
Jan
2019년 4월 29일
A guess:
v = randi([1,50], 1, 1000);
for k = 10:20
m = find(v == k);
if numel(m) < 30
error('Too few elements: %d', k);
elseif numel(m) > 30
v(m(31:end)) = [];
end
end
This contains an iterative shrinking of the vector v, which consumes an exponentially growing amount of resources. As long as the inputs are small (1000 elements seems to be fine), the run-time does not suffer very much. But masking the elements is most likely faster:
v = randi([1,50], 1, 1000);
mask = false(size(v));
for k = 10:20
m = find(v == k);
if numel(m) < 30
error('Too few elements: %d', k);
elseif numel(m) > 30
mask(m(31:end)) = true;
end
end
v(mask) = [];
댓글 수: 0
추가 답변 (1개)
KALYAN ACHARJYA
2019년 4월 28일
편집: KALYAN ACHARJYA
2019년 4월 28일
Followig the code, extract (result) first 30 elements from a, whose value greater than 10 and less than 30.
idx=a>10 & a<30
b=a(idx);
result=b(1:30);
Is the question is aswered as per question? If Not-
Though, I did not undestand the folowing line-
20 should occur 30 times, 24 30 times and so one (10-20 , each 30 times)
Can you eloborate the questions again, what you have (inputs), expected results
(Output Looking for ) and codidtions.
참고 항목
카테고리
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!