Interpreting a Zeros function
3 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
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
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.'
idxSampling1 = [1, interp1(t,1:length(t), 1:19, 'nearest', 'extrap')]
Another way would be
[~, tmp] = min(abs(t(:) - (1:19)),[],1);
idxSampling2 = [1, tmp]
(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 Center 和 File Exchange 中查找有关 Author Block Masks 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!