필터 지우기
필터 지우기

Interpreting a Zeros function

조회 수: 2 (최근 30일)
frozentangled
frozentangled 2021년 1월 29일
댓글: frozentangled 2021년 1월 29일
Hi guys,
I've just received a code and I just can't figure out what this means
idxSampling = zeros(20,1);
idxSampling(1) = 1;
for ii = 1:19
[~,tmp] = min(abs(t-ii));
idxSampling(ii+1) = tmp;
end
I'd be much obliged if someone could tell me what the 'idxSampling' function is trying to achieve
Many thanks in advance!

답변 (1개)

Walter Roberson
Walter Roberson 2021년 1월 29일
idxSampling is not a function there: it is an array.
The code assumes that t is a vector of values. The code is finding the indices into the vector that are closest to 1, 2, 3, 4, 5, and so on up to 19.
t = sort(rand(1,15) * 23 - 1) %some data to use
t = 1×15
0.1225 0.5973 0.7782 4.6402 4.8298 7.9562 10.2478 10.8977 10.9531 12.4351 12.6642 13.4387 17.7164 18.2540 19.4799
In the case that t is all ascending or all descending, another way of writing the code would be
%your existing code
idxSampling = zeros(20,1);
idxSampling(1) = 1;
for ii = 1:19
[~,tmp] = min(abs(t-ii));
idxSampling(ii+1) = tmp;
end
idxSampling.'
ans = 1×20
1 3 3 4 4 5 5 6 6 6 7 9 10 11 12 12 13 13 14 15
idxSampling1 = [1, interp1(t,1:length(t), 1:19, 'nearest', 'extrap')]
idxSampling1 = 1×20
1 3 3 4 4 5 5 6 6 6 7 9 10 11 12 12 13 13 14 15
Another way would be
[~, tmp] = min(abs(t(:) - (1:19)),[],1);
idxSampling2 = [1, tmp]
idxSampling2 = 1×20
1 3 3 4 4 5 5 6 6 6 7 9 10 11 12 12 13 13 14 15
(The interp1 version unexpectedly also works if t is not sorted; it could be the case that unsorted is permited for 'nearest' but not generally.)
  댓글 수: 1
frozentangled
frozentangled 2021년 1월 29일
Thanks! Much obliged!
Have a nice day I hope!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Author Block Masks에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by