Interpreting a Zeros function

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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by