Compare two vectors and keep only equal values

26 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2020-12-16
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 个评论
Max C
Max C 2020-12-17
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 2020-12-17
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by