Compare two vectors and keep only equal values

25 vues (au cours des 30 derniers jours)
Max C
Max C le 16 Déc 2020
Commenté : Star Strider le 17 Déc 2020
Hello!
I have two vectors:
  • 'A' contains integer values from sice 80x1, it is a range of frequencies.
  • 'B' contains floating point values from a measurement of sice 20000x2, B(:,1) lists values between A(1,1) and A(end,1) with a high sampling rate. B(:,2) contains the corresponding sensor data.
I only need to store the data of the frequencies from A. So I use two for loops and an if to store the needed values from B(:,2). But I think this is a bad method. Is there a better way? The if condition also consumes a lot of memory and time (I renamed my variables to better identify their identity):
samplingrate = 20000;
numberoffreq = 80;
b = (samplingrate*(0:(round((numberoffreq)/2)))/(numberoffreq))'; % Vector of all frequency
B = [b,Y0]; % Y0 is the signal with size 200000x2
Y0 = [];
A = round(A,length(num2str(samplingrate))); % Round signals depending on decade of sampling rate. With low sampling rate error between input and output frequencies is higher.
B(:,1) = round(Y0f(:,1),length(num2str(samplingrate)));
szB = size(B,2);
Y0 = zeros(length(A),szB-1); % Preallocation
for i = 1:length(A) % loop over all frquencies in A (80 times)
for j = 1:length(B) % loop over all values in B (200000 times(!!!))
if real(B(j,1))==A(i) % Compare 80*200000(!!!) times if rounded values are equal...
Y0(i,1:szB-1) = B(j,2:szB); % Keep data
end
end
end
Best,
Max

Réponse acceptée

Star Strider
Star Strider le 16 Déc 2020
If you want an exact match, experiment with the ismember function. If you want an approximate match (within a tolerance value), experiment with the ismembertol function.
  2 commentaires
Max C
Max C le 17 Déc 2020
Thank you!
ismembertol does the work for me. I don't know how I overlooked it, because I was testing ismember already.
Max
Star Strider
Star Strider le 17 Déc 2020
As always, my pleasure!
We all overlook functions from time to time. I sometimes find functions that will do exactly what I want, and have been around for at least one previous release, that I somehow missed in my searches.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by