gpt4 book ai didi

c++ - C/C++ 中是否有 accumarray() 的示例

转载 作者:搜寻专家 更新时间:2023-10-31 01:54:59 25 4
gpt4 key购买 nike

我们正在尝试理解 MATLAB 的 accumarray 函数,希望为我们的理解编写相同的 C/C++ 代码。有人可以帮助我们提供示例/伪代码吗?

最佳答案

根据 the documentation ,

The function processes the input as follows:

  1. Find out how many unique indices there are in subs. Each unique index defines a bin in the output array. The maximum index value in subs determines the size of the output array.

  2. Find out how many times each index is repeated.

  3. This determines how many elements of vals are going to be accumulated at each bin in the output array.

  4. Create an output array. The output array is of size max(subs) or of size sz.

  5. Accumulate the entries in vals into bins using the values of the indices in subs and apply fun to the entries in each bin.

  6. Fill the values in the output for positions not referred to by subs. Default fill value is zero; use fillval to set a different value.

因此,转换为 C++(这是未经测试的代码),

template< typename sub_it, typename val_it, typename out_it,
typename fun = std::plus< typename std::iterator_traits< val_it >::value_type >,
typename T = typename fun::result_type >
out_it accumarray( sub_it first_index, sub_it last_index,
val_it first_value, // val_it last_value, -- 1 value per index
out_it first_out,
fun f = fun(), T fillval = T() ) {
std::size_t sz = std::max_element( first_index, last_index ); // 1. Get size.
std::vector< bool > used_indexes; // 2-3. remember which indexes are used

std::fill_n( first_out, sz, T() ); // 4. initialize output

while ( first_index != last_index ) {
std::size_t index = * first_index;
used_indexes[ index ] = true; // 2-3. remember that this index was used
first_out[ index ] = f( first_out[ index ], * first_value ); // 5. accumulate
++ first_value;
++ first_index;
}

// If fill is different from zero, reinitialize untouched values
if ( fillval != T() ) {
out_it fill_it = first_out;
for ( std::vector< bool >::iterator used_it = used_indexes.begin();
used_it != used_indexes.end(); ++ used_it ) {
if ( * used_it ) * fill_it = fillval;
}
}

return first_out + sz;
}

这有一些缺点,例如,累加函数被重复调用,而不是对整个列 vector 调用一次。输出放置在 first_out 引用的预分配存储中。索引 vector 必须与值 vector 大小相同。但大多数功能应该都很好地捕捉到了。

关于c++ - C/C++ 中是否有 accumarray() 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8950807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com