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
댓글 수: 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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!