Extracting first n values of a matrix
212 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Jan
am 29 Apr. 2019
Bearbeitet: Jan
am 29 Apr. 2019
@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?
Akzeptierte Antwort
Jan
am 29 Apr. 2019
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 Kommentare
Weitere Antworten (1)
KALYAN ACHARJYA
am 28 Apr. 2019
Bearbeitet: KALYAN ACHARJYA
am 28 Apr. 2019
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.
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!