Compare two vectors and keep only equal values
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Max C
am 16 Dez. 2020
Kommentiert: Star Strider
am 17 Dez. 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
0 Kommentare
Akzeptierte Antwort
Star Strider
am 16 Dez. 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 Kommentare
Star Strider
am 17 Dez. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!