Compare two vectors and keep only equal values
14 次查看(过去 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
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!