Speeding up to find minimum value using min() function
古いコメントを表示
Hi,
I have to calculate the current distribution of two nonlinear resistors. To do that I’m searching for the closest index and value of an array.
For example.
[a,b]=min(abs(c-s))
c is an n x 1 array. c increases monotonically
c represents the characteristics of the resistors.
s is a 1 x m array and sinusoidal shaped
s represents the impressed current.
With index b I calculate the voltage drop and the current of each resistor.
Any suggestions to speed up the code?
5 件のコメント
Torsten
2022 年 3 月 17 日
c-s will be an nxm matrix and b will be an 1xm vector.
Is it this what you want ?
Michael Walter
2022 年 3 月 17 日
編集済み: Michael Walter
2022 年 3 月 17 日
Jan
2022 年 3 月 17 日
What are typical sizes of the inputs? Do you have a C compiler installed?
Michael Walter
2022 年 3 月 17 日
編集済み: Michael Walter
2022 年 3 月 17 日
Jan
2022 年 3 月 17 日
The size matters, because the creation of the intermediate matrix c-s is time consuming. Then the RAM access is the bottleneck.
採用された回答
その他の回答 (2 件)
Matt J
2022 年 3 月 17 日
c=c(:)';
b=interp1(c,1:numel(c),s,'nearest');
a=abs(c(b)-s)
c = c(:); % Make it a column vector to be sure
nc = numel(c);
bin = [c(1); (c(1:nc-1) + c(2:nc)) * 0.5; c(nc)];
[~, idx] = histc(s, bin);
value = abs(c(idx) - s(:));
bin contains the start point, midpoints and final point of the intervals of c.
histc uses a binary search to find the index of the value in c for each element of s. This avoids to create the large matrix c - s. Unfortunately MathWorks decided to replace the working histc by histcounts, which has some performance problems.
See also: interp1('nearest')
c = linspace(0, 1, 1e4);
s = rand(1, 1e5);
tic;
[a, b] = min(abs(c(:) - s(:).'));
toc
tic;
c = c(:);
nc = numel(c);
bin = [c(1); (c(1:nc-1) + c(2:nc)) * 0.5; c(nc)];
[~, b2] = histc(s, bin);
% Alternative, seems to be faster:
% [~, ~, b2] = histcounts(s, bin);
a2 = abs(c(b2) - s(:));
toc
isequal(b, b2)
max(abs(a(:) - a2(:)))
4 件のコメント
Michael Walter
2022 年 3 月 17 日
編集済み: Michael Walter
2022 年 3 月 17 日
Can you provide some input data, which reproduce the problem?
HISTC replies 0, if the data are not inside the bins. So you can expand the first an last bins to the maximal values of s:
% bin = [c(1); (c(1:nc-1) + c(2:nc)) * 0.5; c(nc)]; % Original
bin = [min(s); (c(1:nc-1) + c(2:nc)) * 0.5; max(s)];
If you know the values in advance, you can save the time for searching min and max.
Michael Walter
2022 年 3 月 18 日
編集済み: Michael Walter
2022 年 3 月 18 日
Michael Walter
2022 年 3 月 18 日
カテゴリ
ヘルプ センター および File Exchange で MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
