Extracting first n values of a matrix
212 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Jan
il 29 Apr 2019
Modificato: Jan
il 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?
Risposta accettata
Jan
il 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 Commenti
Più risposte (1)
KALYAN ACHARJYA
il 28 Apr 2019
Modificato: KALYAN ACHARJYA
il 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.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!